What is the most efficient, "cheap" and accurate way to measure time in Java in resolution of microseconds?

587 views Asked by At

I'm using ASM java byte code instrumentation and my goal is to measure the time in each access to a variable.

** measure time and log **

** variable access **

I'm looking for a resolution of microseconds. It should be accurate and therefore "cheap" enough (meaning that I don't want a function or a library that will take 10 ms to get the time).

I've tried System.NanoTime() (too much, and costly) and Calendar (too loose), but I'm looking for a better alternative.

2

There are 2 answers

2
fmucar On BEST ANSWER

System.nanotime() is a native method call, if that is too costly for you , then you probably wont be able to find something suitable to your needs in java.

I dont think System.nanotime() will ever take 10ms (unless you specifically do something just to slow it down) to execute ever as well.

And finally, I am not sure if micro seconds will be precise enough for property access times, nanoseconds may be more useful.

0
Stephen C On

... I don't want a function or a library that will take 10 ms to get the time

Firstly, you are exaggerating. System.nanoTime() does not take 10 milliseconds.

Secondly, I don't think there is a faster way in pure Java. You might possibly be able to access a system clock faster from native code, but your code will be platform specific. (Besides, my gut feeling is that System.nanoTime() will do it as fast as possible.)


Accessing a variable may take as little as a couple of machine instruction, depending on the context and the kind of variable you are accessing. This likely to be swamped by the time taken access a system timer.

Furthermore the insertion of method calls to a clock method before a variable access may make the variable access take longer. The method call is liable to invalidate the content of registers, causing the code generator to insert instructions to refetch the variable from memory.

In short, insertion of the code to fetch the clock times is liable to give you unreliable and misleading timing numbers. You can potentially get more meaningful numbers by timing LONG sequences of instructions ... but even that can give you bogus numbers if you make mistakes in your benchmarking methodology.