Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Precise time measurement in Java

Java gives access to two method to get the current time: System.nanoTime() and System.currentTimeMillis(). The first one gives a result in nanoseconds, but the actual accuracy is much worse than that (many microseconds).

Is the JVM already providing the best possible value for each particular machine? Otherwise, is there some Java library that can give finer measurement, possibly by being tied to a particular system?

like image 521
penpen Avatar asked Sep 30 '09 22:09

penpen


People also ask

How to measure time in Java code?

There are two ways to measure elapsed execution time in Java either by using System. currentTimeinMillis()or by using System. nanoTime(). These two methods can be used to measure elapsed or execution time between two method calls or events in Java.

How accurate is system nanoTime?

nanoTime() is a great function, but one thing it's not: accurate to the nanosecond. The accuracy of your measurement varies widely depending on your operation system, on your hardware and on your Java version. As a rule of thumb, you can expect microsecond resolution (and a lot better on some systems).

How to calculate time in nanoseconds in Java?

long estimatedTime = System. nanoTime() - startTime; The above code snippet returns the current value of the time in nanoseconds. The value returned by System.


1 Answers

The problem with getting super precise time measurements is that some processors can't/don't provide such tiny increments.

As far as I know, System.currentTimeMillis() and System.nanoTime() is the best measurement you will be able to find.

Note that both return a long value.

like image 118
jjnguy Avatar answered Nov 02 '22 21:11

jjnguy