Java System nanoTime() Method
Example
Measure how long a loop takes, in nanoseconds:
public class Main {
public static void main(String[] args) {
long start = System.nanoTime();
int sum = 0;
for (int i = 0; i < 1000; i++) {
sum += i;
}
long end = System.nanoTime();
System.out.println("The loop took " + (end - start) + " nanoseconds");
}
}
Note: The output is different each time you run the program.
Definition and Usage
The nanoTime() method returns the current value of the most exact timer in the system, in nanoseconds (billionths of a second).
The value does not tell the time of day. Use it to measure how much time passes between two points in a program: call it before and after, and subtract the first value from the second.
Tip: To get the time of day, use the currentTimeMillis() method.
Syntax
public static long nanoTime()
Parameter Values
None.
Technical Details
| Returns: | A long value, the current value of the timer in nanoseconds. |
|---|
Related Pages
❮ System Methods