Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java high precision stopwatch

Tags:

java

stopwatch

I have this problem, and I can't get any idea how to solve it.
I have to measure the time needed to perform certain function. Okay, stopwatch function that measure time in milliseconds wasn't good enough, so I used measurement in nano seconds.

The problem is, function ends so fast, even stopwatch in nano seconds can't measure it.

I know that stopwatch works, because I tried to put for example Thread.sleep(1) in my function (Thread.sleep is in milliseconds), and I get my time, but without Thread.sleep, my time is always 0. Any ideas?

Here is my code:

long startTimeLocalNS=0;
long stopTimeLocalNS = 0;
startTimeLocalNS = System.nanoTime();
if (something)
{
    /*my Code;*/
}   
stopTimeLocalNS = System.nanoTime();
disconnectTime = (stopTimeLocalNS - startTimeLocalNS);
like image 492
CRT_flow Avatar asked Dec 28 '22 00:12

CRT_flow


1 Answers

How about running the function a few thousand (or million) times in a loop, measuring the total time and dividing it by the number of iterations?

But beware the many pitfalls in writing microbenchmarks.

like image 130
Michael Borgwardt Avatar answered Dec 30 '22 15:12

Michael Borgwardt