Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Measure execution time for a Java method [duplicate]

Tags:

java

How do I calculate the time taken for the execution of a method in Java?

like image 508
Renuka Avatar asked Aug 01 '10 17:08

Renuka


People also ask

How do I measure time elapsed in Java?

The now() method of the Instant class returns the current time and the Duration. between() methods returns the difference between the given two time values to get the elapsed time retrieve the time values before and after the execution of the desired method and retrieve the duration using the Duration.

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.

How do you record seconds in Java?

To compute the elapsed time of an operation in seconds in Java, we use the System. currentTimeMillis() method.


2 Answers

To be more precise, I would use nanoTime() method rather than currentTimeMillis():

long startTime = System.nanoTime(); myCall();  long stopTime = System.nanoTime(); System.out.println(stopTime - startTime); 

In Java 8 (output format is ISO-8601):

Instant start = Instant.now(); Thread.sleep(63553); Instant end = Instant.now(); System.out.println(Duration.between(start, end)); // prints PT1M3.553S 

Guava Stopwatch:

Stopwatch stopwatch = Stopwatch.createStarted(); myCall(); stopwatch.stop(); // optional System.out.println("Time elapsed: "+ stopwatch.elapsed(TimeUnit.MILLISECONDS)); 
like image 103
Vitalii Fedorenko Avatar answered Oct 05 '22 08:10

Vitalii Fedorenko


You can take timestamp snapshots before and after, then repeat the experiments several times to average to results. There are also profilers that can do this for you.


From "Java Platform Performance: Strategies and Tactics" book:

With System.currentTimeMillis()

class TimeTest1 {    public static void main(String[] args) {        long startTime = System.currentTimeMillis();        long total = 0;       for (int i = 0; i < 10000000; i++) {          total += i;       }        long stopTime = System.currentTimeMillis();       long elapsedTime = stopTime - startTime;       System.out.println(elapsedTime);    } } 

With a StopWatch class

You can use this StopWatch class, and call start() and stop before and after the method.

class TimeTest2 {    public static void main(String[] args) {        Stopwatch timer = new Stopwatch().start();        long total = 0;       for (int i = 0; i < 10000000; i++) {          total += i;       }        timer.stop();       System.out.println(timer.getElapsedTime());    } } 

See here (archived).


NetBeans Profiler:

Application Performance Application

Performance profiles method-level CPU performance (execution time). You can choose to profile the entire application or a part of the application.

See here.

like image 33
bakkal Avatar answered Oct 05 '22 08:10

bakkal