问题
Here is my code.
int hours = (int) (timeElapsed / 3600000);
int minutes = (int) (timeElapsed - hours * 3600000) / 60000;
int seconds = (int) (timeElapsed - hours * 3600000 - minutes * 60000) / 1000;
I need to now calculate MilliSeconds that runs really fast.
Please help me how?
回答1:
One way to speed up things is to minimize the run-time mathematical operations by reusing some of the intermediate calculations. Adding some constants, whose calculation is done at compile-time, will increase readability. Assuming timeElapsed is an int, you can also remove the casting.
final int MILLISECONDS_PER_SECOND = 1000;
final int MILLISECONDS_PER_MINUTE = 60 * MILLISECONDS_PER_SECOND;
final int MILLISECONDS_PER_HOUR = 60 * MILLISECONDS_PER_MINUTE;
int hours = timeElapsed / MILLISECONDS_PER_HOUR;
timeElapsed -= hours * MILLISECONDS_PER_HOUR;
int minutes = timeElapsed / MILLISECONDS_PER_MINUTE;
timeElapsed -= minutes * MILLISECONDS_PER_MINUTE;
int seconds = timeElapsed / MILLISECONDS_PER_SECOND;
timeElapsed -= seconds * MILLISECONDS_PER_SECOND;
int millis = timeElapsed;
The last two lines could be combined for a bit more speed, but the symmetry looked nice. :-)
回答2:
Based on your existing logic, try this.
int millis = (int) (timeElapsed - hours * 3600000 -
minutes * 60000 - seconds * 1000);
回答3:
It's probably not incredibly fast, but you can do int millis = timeElapsed %1000; If you're looking for a simple calculation. It might run faster if an optimizer realized it's not dependent on the previous variables. That being said, modulo is an expensive operation compared to addition, multiplication, and subtraction.
回答4:
int(millis() / 3600000); //HORAS - H
int((millis() % 3600000) / 60000); //MINUTOS - M
int(((millis() % 3600000) % 60000) / 1000); //SEGUNDOS - S
int(((millis() % 3600000) % 60000) % 1000); //MILESIMAS SEGUNDO - MS
:)
来源:https://stackoverflow.com/questions/22237587/get-millisecond-to-display-in-android-decive