tags:

views:

294

answers:

2

I'm timing some things, which I can't just put in a long loop. And I need to time them to see how long they take to complete, but it seems like the timer has a 15-16 ms accuracy in java? How can i get around this?

+4  A: 

Have you tried using System.nanoTime()?

From the Javadoc:

Returns the current value of the most precise available system timer, in nanoseconds.

This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary time (perhaps in the future, so values may be negative). This method provides nanosecond precision, but not necessarily nanosecond accuracy. No guarantees are made about how frequently values change. Differences in successive calls that span greater than approximately 292 years (263 nanoseconds) will not accurately compute elapsed time due to numerical overflow.

For example, to measure how long some code takes to execute:

long startTime = System.nanoTime(); // ... the code being measured ... long estimatedTime = System.nanoTime() - startTime;

John Meagher
heh, I love that sentence: "Differences in successive calls that span greater than approximately 292 years (263 nanoseconds) will not accurately compute elapsed time due to numerical overflow." There should be a contest for the longest-running software program without interruption/malfunction.
Jason S
+2  A: 

Clocks and Timers - General Overview

Java Programming API's for Clocks and Timers The absolute "time-of-day" clock is represented by the System.currentTimeMillis() method, that returns a millisecond representation of wall-clock time in milliseconds since the epoch. As such it uses the operating system's "time of day" clock. The update resolution of this clock is often the same as the timer interrupt (eg. 10ms), but on some systems is fixed, independent of the interrupt rate.

The relative-time clock is represented by the System.nanoTime() method that returns a "free-running" time in nanoseconds. This time is useful only for comparison with other nanoTime values. The nanoTime method uses the highest resolution clock available on the platform, and while its return value is in nanoseconds, the update resolution is typically only microseconds. However, on some systems there is no choice but to use the same clock source as for currentTimeMillis() - fortunately this is rare and mostly affects old Linux systems, and Windows 98.

Mitch Wheat