Measure Execution Time for a Java Method

How do I time a method's execution in Java?

There is always the old-fashioned way:

long startTime = System.nanoTime();
methodToTime();
long endTime = System.nanoTime();

long duration = (endTime - startTime); //divide by 1000000 to get milliseconds.

How to measure the execution time with Java

In order for this to work, this line:

long start = System.currentTimeMillis(); 

should be before this line:

ob.sort(nums, 0, nums.length-1);

Also, keep in mind this is measuring Time and not Time Complexity

How can i benchmark method execution time in java?

Other than using a profiler, a simple way of getting what you want is the following:

public class SomeClass{
public void somePublicMethod()
{
long startTime = System.currentTimeMillis();
someMethodWhichYouWantToProfile();
long endTime = System.currentTimeMillis();
System.out.println("Total execution time: " + (endTime-startTime) + "ms");
}
}

How to Measure execution time for a multi threaded task in java

If you wish to get a rough idea of the time the whole set of operations takes then use shutdown then awaitTermination to wait for the executor service to finish all of the submitted tasks. Here is a simple example:

long start= System.nanoTime();
ExecutorService exec = Executors.newFixedThreadPool(100);
try {
for (int i = 0; i < 100_000; i++) {
final int x = i;
Runnable runnable = () -> System.out.println(x);
exec.submit(runnable);
}
} finally {
exec.shutdown();
exec.awaitTermination(365, TimeUnit.DAYS);
}
long elapsed = System.nanoTime() - start;
System.out.println("Elapsed millisec "+TimeUnit.NANOSECONDS.toMillis(elapsed));

It's not a good idea to put System.out.println or other logging inside the tasks as then you are only timing your console I/O, and not getting an estimate of how quick your processing is.

As in the comments, using multi-thread access to same set of servers / resource / disk can make overall elapsed time get longer or cause issues elsewhere.

From JDK19 the ExecutorService is AutoCloseable so you can simplify the try block and remove the finally:

try (ExecutorService exec = Executors.newFixedThreadPool(100)) {
...
}

What's a clean way to time code execution in Java?

You solution is just fine.

A less expressive way would be to wrap your code to be timed in a lambda.

public void timeCode(Runnable code) {
...
try {
code.run();
} catch ...
}
...
}

timeCode(() -> { ...code to time... });

You would probably like to catch the checked exceptions and pass them to some runtime exception or whatever.

measuring execution time in java

long startTime = new Date().getTime();
doSomething();
long endTime = new Date().getTime();
System.out.println("elapsed milliseconds: " + (endTime - startTime));


Related Topics



Leave a reply



Submit