views:

58

answers:

3

I want to capture the time take to go from statement A to Statement B in a Java class. In between these statements there are many web service calls made. I wanted to know if there is some stop watch like functionality in java that i could use to capture the exact time?

Kaddy

+5  A: 

This will give you the number of nanoseconds between the two nanoTime() calls.

long start = System.nanoTime();
// Java statements
long diff = System.nanoTime() - start;

For more sophisticated approaches there are several duplicate questions that address Stopwatch classes:

Ben S
A: 

System.currentTimeMillis will get it in milliseconds and nanoTime in nanosceconds.

If you're trying to compare the performance of different techniques, note that the JVM environment is complex so simply taking one time is not meaningful. I always write a loop where I execute method 1 a few thousand times, then do a System.gc, then execute method 2 a few thousands times, then do another System.gc, then loop back and do the whole thing again at least five or six times. This helps to average out time for garbage collection, just-in-time compiles, and other magic things happening in the JVM.

Jay
+1  A: 

@Ben S's answer is spot on.

However, it should be noted that the approach of inserting time measurement statements into your code does not scale:

  • It makes your code look a mess.
  • It makes your application run slower. Those calls to System.nanoTime() don't come for free!
  • It introduces the possibility of bugs.

If your real aim is to try and work out why your application is running slowly so that you decide what what to optimize, then a better solution is to use a Java profiler. This has the advantage that you need to make ZERO changes to your source code. (Of course, profiling doesn't give you the exact times spent in particular sections. Rather, it gives you time proportions ... which is far more useful for deciding where to optimize.)

Stephen C