Measuring Execution Time in Nanoseconds in Java
February 9th, 2009 by
peasleer
Sometimes measuring time using the trusty System.currentTimeMillis() static call isn’t of high enough resolution to measure the execution time of methods with any meaning. Fortunately for those facing this problem, Java 5 introduced a method of accessing the system’s most precise clock through the System.nanoTime() static call. This returns a long that represents the current clock time in nanoseconds, easily solving the problem of measuring time more precisely than milliseconds can provide.
Thus ends another quick post, get back to work :)
Though I’m sure you’re using this method responsibly, it is important to note the inherent issues with using such a function to measure time. This bug report, specifically the Sun Developer’s evaluation, addresses the most important issues (quoted from: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6519418):
- only use nanoTime values to compare against other nanoTime values obtained from within the same VM
- resolution (ie the smallest observable update) is dependent on OS and hardware platform but is never worse than currentTimeMillis(). I don’t think giving examples is appropriate, but something like “on an operating system with good hardware support a resolution on the order of tens of microseconds is not uncommon”
I also think it is worth pointing out that to compare two nanoTime values,
long t0 = System.nanoTime();
…
long t1 = System.nanoTime();
one should not do
t0 < t1
but instead do
t1 – t0 < 0
because of overflow
Feb 10th, 2009 at 3:46 pm
Good tips, thanks for sharing. Yes, for the record, I was using them responsibly (difference of times only, no comparisons, and I was aware that their precision was limited by the most precise clock available). I hadn’t read the bug report though, which is also good information to have. Thanks again Dave :)
Feb 10th, 2009 at 11:58 pm