How to find time taken to run a Java program?
You can compare times using System.nanoTime()
. It will return the time in nanoseconds.
Returns the current value of the most precise available system timer, in nanoseconds.
You could use it like this:
long startTime = System.nanoTime();
// code
long endTime = System.nanoTime();
System.out.println("Took "+(endTime - startTime) + " ns");
Usefull links:
System.nanoTime()
If you have Spring as a dependency of your project (or don't mind adding it), you can use StopWatch
. As the name suggests, once initialized it will count the time until you stop it. You can then check the time taken for a task. Multiple StopWatches can be used simultaneously to multiple tasks keeping the code clean.
Besides keeping your code clean, StopWatches help with formatting the time and other utility methods.
public void myMethod(){
StopWatch stopWatch = new StopWatch();
stopWatch.start("Task1");
// ...
// Do my thing
// ...
stopWatch.stop();
System.out.println("Task executed in " + stopWatch.getTotalTimeSeconds() + "s");
}
There is no built-in way to see for how long your program has been running. However, you could at the start of the program just store the current time, so that sometime later you can see how much time has elapsed.
public class MyProgram {
private static long startTime = System.currentTimeMillis();
public static void main(String[] args) {
// Do stuff...
// At the end
long endTime = System.currentTimeMillis();
System.out.println("It took " + (endTime - startTime) + " milliseconds");
}
}