I want to show a formatted string with minutes, seconds, and only one character of milliseconds. This is what I put together (mostly from other posts around here):
public static final String getTimeDurationAsString(long milliseconds) {
int millis = (int) (milliseconds % 1000);
int seconds = (int) (milliseconds / 1000) % 60;
int minutes = (int) ((milliseconds / (1000*60)) % 60);
int hours = (int) ((milliseconds / (1000*60*60)) % 24);
StringBuilder sb = new StringBuilder();
if (hours > 0) {
sb.append(String.format("%02d", hours));
sb.append(":");
}
sb.append(String.format("%02d", minutes));
sb.append(":");
sb.append(String.format("%02d", seconds));
sb.append(".");
sb.append(String.format("%03d", millis).substring(0, 1));
return sb.toString();
}
So I will hide the hours position if the duration didn’t exceed 59.9 minutes (which will usually be the case). I did a pretty bad substring() for the milliseconds position just to grab the first digit. Is there a better way to do the above? I’d like strings like:
00:14.9
00:05.1
00:05.2
33:20:4
etc
I have to generate this string repeatedly for a game I’m making (the above rendered every frame) so afraid it’s doing a lot of unnecessary work?
Thanks!
Without a doubt there are more efficient ways to code this up (there are practically always are).
However, on my box your function can format ~130,000 timestamps per second. Clearly, this is plenty fast enough for your stated use case.
That said, if I were coding this up and thought a priori that it’s likely to be on the performance-critical path, I’d avoid
String.format():On my box this can do about 8 million conversions per second. It also creates significantly fewer temporary objects that end up having to be garbage collected.