How to calculate the running time of my program?
To calculate the running time of a program in Java, you can use the System.currentTimeMillis()
method to get the current time in milliseconds before and after the program runs. You can then subtract the start time from the end time to get the elapsed time.
Here is an example of how you can calculate the running time of a program in Java:
long startTime = System.currentTimeMillis();
// Run the program here
long endTime = System.currentTimeMillis();
long elapsedTime = endTime - startTime;
System.out.println("Elapsed time: " + elapsedTime + " milliseconds");
This code gets the current time in milliseconds before and after the program runs and calculates the elapsed time in milliseconds. It then prints the elapsed time to the console.
You can use the elapsedTime
variable to get the elapsed time in other units, such as seconds or minutes. For example:
long elapsedTimeInSeconds = elapsedTime / 1000;
long elapsedTimeInMinutes = elapsedTime / 60000;
This code calculates the elapsed time in seconds and minutes, respectively.
Note that the System.currentTimeMillis()
method may not be accurate on systems with a slow clock. You can use the System.nanoTime()
method instead to get a more accurate measurement of the elapsed time.