Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find time taken to run a Java program?

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?

like image 976
MK1 Avatar asked Jul 11 '11 06:07

MK1


People also ask

How do you calculate time taken to run a method in Java?

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.

How do you time how long a program takes in Java?

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.

How do you calculate Execution time?

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.

Is there a time function in Java?

The time functions can be accessed from the java. util. Date class. This represents an instance of time with millisecond precision.


2 Answers

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()
like image 159
jmj Avatar answered Oct 13 '22 07:10

jmj


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");     } } 
like image 42
Jesper Avatar answered Oct 13 '22 08:10

Jesper