How do I calculate the time taken for the execution of a method in Java?
-
1lol, that is a lot of duplicates :D too bad that when you close a question you can only name one :(IAdapter– IAdapter2010-08-01 20:53:17 +00:00Commented Aug 1, 2010 at 20:53
-
1Here is a stopwatch class for java. This formats the time output as .NET's Stopwatch class carlosqt.blogspot.com/2011/05/stopwatch-class-for-java.htmlCarlos Quintanilla– Carlos Quintanilla2011-07-22 12:07:55 +00:00Commented Jul 22, 2011 at 12:07
-
You forgot to mention explicitly the purpose of the measurement, which might have influence on the way it should be done. Anyway it sounds like you want to do performance optimization. In that case you should definitely read about "Micro Benchmarking". While the System.nanoTime() approach is quite simple, there is no easy way, to measure program performance exactly, because it depends on so many different factors (e.g. hardware, other software running on the same system, just-in-time and hot-spot compilation, input data etc.).user573215– user5732152013-01-07 10:56:41 +00:00Commented Jan 7, 2013 at 10:56
-
This is a Stopwatch I made, it's very simple to use. gist.github.com/juanmf/4147a9b7010c7b04c003juanmf– juanmf2015-11-08 00:23:14 +00:00Commented Nov 8, 2015 at 0:23
8 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));
8 Comments
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.
4 Comments
currentTimeMillis rather than nanoTime. You probably don't want to the timer cod ein the method under test. To get an idea of warm up time and variation between results, I tend to put in an outer loop to repeat the timing five times.Check this: System.currentTimeMillis.
With this you can calculate the time of your method by doing:
long start = System.currentTimeMillis();
class.method();
long time = System.currentTimeMillis() - start;
4 Comments
In case you develop applications for Android you should try out the TimingLogger class.
Take a look at these articles describing the usage of the TimingLogger helper class:
- Measuring performance in the Android SDK (27.09.2010)
- Discovering the Android API - Part 1 (03.01.2017)
3 Comments
You might want to think about aspect-oriented programming. You don't want to litter your code with timings. You want to be able to turn them off and on declaratively.
If you use Spring, take a look at their MethodInterceptor class.
Comments
If you are currently writing the application, than the answer is to use System.currentTimeMillis or System.nanoTime serve the purpose as pointed by people above.
But if you have already written the code, and you don't want to change it its better to use Spring's method interceptors. So for instance your service is :
public class MyService {
public void doSomething() {
for (int i = 1; i < 10000; i++) {
System.out.println("i=" + i);
}
}
}
To avoid changing the service, you can write your own method interceptor:
public class ServiceMethodInterceptor implements MethodInterceptor {
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
long startTime = System.currentTimeMillis();
Object result = methodInvocation.proceed();
long duration = System.currentTimeMillis() - startTime;
Method method = methodInvocation.getMethod();
String methodName = method.getDeclaringClass().getName() + "." + method.getName();
System.out.println("Method '" + methodName + "' took " + duration + " milliseconds to run");
return null;
}
}
Also there are open source APIs available for Java, e.g. BTrace. or Netbeans profiler as suggested above by @bakkal and @Saikikos. Thanks.
Comments
As proposed nanoTime () is very precise on short time scales. When this precision is required you need to take care about what you really measure. Especially not to measure the nanotime call itself
long start1 = System.nanoTime();
// maybe add here a call to a return to remove call up time, too.
// Avoid optimization
long start2 = System.nanoTime();
myCall();
long stop = System.nanoTime();
long diff = stop - 2*start2 + start1;
System.out.println(diff + " ns");
By the way, you will measure different values for the same call due to
- other load on your computer (background, network, mouse movement, interrupts, task switching, threads)
- cache fillings (cold, warm)
- jit compiling (no optimization, performance hit due to running the compiler, performance boost due to compiler (but sometimes code with jit is slower than without!))
Comments
Nanotime is in fact not even good for elapsed time because it drifts away signficantly more than currentTimeMillis. Furthermore nanotime tends to provide excessive precision at the expense of accuracy. It is therefore highly inconsistent,and needs refinement.
For any time measuring process,currentTimeMillis (though almost as bad), does better in terms of balancing accuracy and precision.