I have a Java application that I've been working on and I just realized that the program has to return a value in less than a minute, but don't know how to find or display the time taken to run the program. How to find time taken to run a program?
The currentTimeMillis() method returns the current time in milliseconds. To find the elapsed time for a method you can get the difference between time values before and after the execution of the desired method. The nanoTime() method returns the current time in nano seconds.
There are two ways to measure elapsed execution time in Java either by using System. currentTimeinMillis()or by using System. nanoTime(). These two methods can be used to measure elapsed or execution time between two method calls or events in Java.
The difference between the end time and start time is the execution time. Get the execution time by subtracting the start time from the end time.
The time functions can be accessed from the java. util. Date class. This represents an instance of time with millisecond precision.
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()
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"); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With