|
Do you need help with your Java programming?
Click here for instant help with your Java code. |
Measure Time in Nano-Seconds
Since computers are getting faster and faster it might be insufficient to measure the time a certain task takes using only milli-seconds. Since Java 5, the System class has a new method, nanoTime, that returns a nanosecond-resolution counter. You can’t use it for measuring absolute time, but it works great for measuring time differences. The example below shows how to use it: |
package com.javadb.examples; public class Main { public static void main(String[] args) { long start = System.nanoTime(); for (int i = 0; i < 10; i++) { System.out.println(i); } long end = System.nanoTime(); System.out.println("Time: " + (end - start)); } } |
Unfortunately, we have no guarantee that we will actually get nano-second measurements when we run this code. But with a faster machine and a good JRE implementation, it’s a useful measurement for testing purposes. You can find more information on this method in the JDK 5 documentation. Because of operating system characteristics, machine processing speed, and system load, you may get a wide variation in the values returned by the nanoTime method. This is what the output was when run on the Javadb.com machine :) |
0 1 2 3 4 5 6 7 8 9 Time: 824547 |
| Do you know your Java? | |
| Take a Ten-Question-Java-Quiz! | |
Search for code examples on this site
