Java calculate elapsed time example
package com.w3schools;
import java.util.concurrent.TimeUnit;
public class ElapsedTimeTest {
public static void main(String args[]) throws InterruptedException{
//start
long lStartTime = System.nanoTime();
//task
calculation();
//end
long lEndTime = System.nanoTime();
//time elapsed
long output = lEndTime - lStartTime;
System.out.println("Elapsed time in milliseconds: " + output / 1000000);
}
private static void calculation() throws InterruptedException {
//Sleep 3 seconds
TimeUnit.SECONDS.sleep(3);
}
} |
package com.w3schools;
import java.util.concurrent.TimeUnit;
public class ElapsedTimeTest {
public static void main(String args[]) throws InterruptedException{
//start
long lStartTime = System.nanoTime();
//task
calculation();
//end
long lEndTime = System.nanoTime();
//time elapsed
long output = lEndTime - lStartTime;
System.out.println("Elapsed time in milliseconds: " + output / 1000000);
}
private static void calculation() throws InterruptedException {
//Sleep 3 seconds
TimeUnit.SECONDS.sleep(3);
}
}
Output:
Elapsed time in milliseconds: 3002 |
Elapsed time in milliseconds: 3002