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?
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.
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).
long estimatedTime = System. nanoTime() - startTime; The above code snippet returns the current value of the time in nanoseconds. The value returned by System.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With