How to calculate the running time of my program? [duplicate]
Solution 1:
Use System.nanoTime to get the current time.
long startTime = System.nanoTime();
.....your program....
long endTime = System.nanoTime();
long totalTime = endTime - startTime;
System.out.println(totalTime);
The above code prints the running time of the program in nanoseconds.
Solution 2:
At the beginning of your main method, add this line of code :
final long startTime = System.nanoTime();
And then, at the last line of your main method, you can add :
final long duration = System.nanoTime() - startTime;
duration
now contains the time in nanoseconds that your program ran. You can for example print this value like this:
System.out.println(duration);
If you want to show duration time in seconds, you must divide the value by 1'000'000'000. Or if you want a Date
object: Date myTime = new Date(duration / 1000);
You can then access the various methods of Date
to print number of minutes, hours, etc.
Solution 3:
Use System.currentTimeMillis() or System.nanoTime() if you want even more precise reading. Usually, milliseconds is precise enough if you need to output the value to the user. Moreover, System.nanoTime()
may return negative values, thus it may be possible that, if you're using that method, the return value is not correct.
A general and wide use would be to use milliseconds :
long start = System.currentTimeMillis();
...
long end = System.currentTimeMillis();
NumberFormat formatter = new DecimalFormat("#0.00000");
System.out.print("Execution time is " + formatter.format((end - start) / 1000d) + " seconds");
Note that nanoseconds are usually used to calculate very short and precise program executions, such as unit testing and benchmarking. Thus, for overall program execution, milliseconds are preferable.