This example shows us how to use the System.nanoTime()
method to get the amount of time a process take place. Please be aware that the nano time value is not related to the real world time value.
package org.kodejava.lang;
public class ElapsedTimeExample {
public static void main(String[] args) {
// Get the start time of the process
long start = System.nanoTime();
System.out.println("Start: " + start);
// Just do some a bit long process calculating the total value
// of even number from zero to 10000
int totalEven = 0;
for (int i = 0; i < 10000; i++) {
if (i % 2 == 0) {
totalEven = totalEven + i;
}
}
// Get the end time of the process
long end = System.nanoTime();
System.out.println("End : " + end);
long elapsedTime = end - start;
// Show how long it took to finish the process
System.out.println("The process took approximately: "
+ elapsedTime + " nano seconds");
}
}
And example of the result are:
Start: 35034476484699
End : 35034477434200
The process took approximately: 949501 nano seconds
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024