I wrote a program and now I want to calculate the total running time of my program from start to end.
How can I do this?
I wrote a program and now I want to calculate the total running time of my program from start to end.
How can I do this?
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.
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.
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.
The general approach to this is to:
main()
.main()
.A hint: look at System.nanoTime()
or System.currentTimeMillis()
.
You need to get the time when the application starts, and compare that to the time when the application ends.
Wen the app starts:
Calendar calendar = Calendar.getInstance();
// Get start time (this needs to be a global variable).
Date startDate = calendar.getTime();
When the application ends
Calendar calendar = Calendar.getInstance();
// Get start time (this needs to be a global variable).
Date endDate = calendar.getTime();
To get the difference (in millseconds), do this:
long sumDate = endDate.getTime() - startDate.getTime();
Beside the well-known (and already mentioned) System.currentTimeMillis()
and System.nanoTime()
there is also a neat library called perf4j which might be useful too, depending on your purpose of course.