I’m executing a Runnable within an Android application every 100ms wrapped in a Java ScheduledExecutorService. As a part of the run() block I need to obtain the current seconds as 0-59 and milliseconds as 0-999. Both should be in local time, although UTC is workable too.
What’s the absolute fastest way to do this? Internationalization/unique calendars aren’t required.
Currently I’m using Calendar in the below way, but I was thinking it could be faster to use System.currentTimeMillis() and do some math, I’d appreciate any input.
Calendar calendar = Calendar.getInstance();
int seconds = calendar.get(Calendar.SECOND);
If it’s relevant, this is actually within an Android application.
Edit for clarification
Obtaining the current seconds as 0-59 (i.e. relative to the current minute) is critical, so System.currentTimeMillis() comes with a math cost as I mentioned above. What I wasn’t sure about was whether doing this math + the system call would be faster than the call to Calendar, or if there are any other options (like Joda Time) which may have even less of a footprint.
For reference, below is the most straightforward way I could come up with off the top of my head to get seconds (0-59) from the Unix timestamp.
double seconds = Math.floor(((Math.floor(System.currentTimeMillis() / 1000) % 86400) % 3600) % 60);
You won’t find anything faster than
System.currentTimeMillis().That said, fast and correct don’t necessarily go hand-in-hand. As always: consider using Joda Time. You’re just not going to be able to hit all the edge cases correctly without a library.