Capturing runtime between two Java statements?

I want to take the time to go from statement A to Statement B in a Java class. Between these statements, many web service calls have been made. I wanted to know if there is some kind of stopwatch function, for example, in java, which I could use to fix the exact time?

Kaddy

+6
java time stopwatch
source share
3 answers

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

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

For more complex approaches, there are several recurring questions that relate to stopwatch classes:

  • Java Performance Sync Library
  • Stopwatch for Java
+12
source share

@ Ben S answer is in place.

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

  • This turns your code into a mess.
  • This makes your application run slower. Those calls to System.nanoTime() do not come for free!
  • He introduces the possibility of errors.

If your real goal is to try to find out why your application is slow, so you decide what to optimize, then using the Java profiler is the best solution. This has the advantage that you need to make ZERO changes to the source code. (Of course, profiling does not give you the exact time spent in certain sections. Rather, it gives you time proportions ... which is much more useful for deciding where to optimize.)

+2
source share

System.currentTimeMillis will receive it in milliseconds and nanoTime in nanoseconds.

If you are trying to compare the performance of different methods, note that the JVM environment is complex, so it just doesn't make sense once. I always write a loop where I execute method 1 several thousand times, then execute System.gc, then execute method 2 several thousand times, then do another System.gc, then finish back and do it all at least five times or six time. This helps to average the time of garbage collection, on-time compilation, and other magical things happening in the JVM.

0
source share

All Articles