Konrad Reiche
Konrad Reiche

Reputation: 29493

Measuring method execution with JVMTI

Using the MethodEntry and MethodExit event hooks provided by the JVMTI how would I measure the time of a method executed in Java?

In simple means it's just: time2 - time1 but the problem I see, how to I distinguish between the different methods? There is a methodID, but what about recursive calls? When is a method closed after it was opened?

Should I compare the stack trace? What would be a meaningful data structure to trace the methods which where entered? Something like Map<StackTrace,Time>?

Upvotes: 1

Views: 648

Answers (1)

x4u
x4u

Reputation: 14077

You will need a stack for every thread and and with every MethodEnter you push the timestamp on the stack and on MethodExit you pop the timestamp and calculate the difference to the current time.

Although you should keep in mind that reading timestamps or tickcounts and also the surrounding logic is comparatively time consuming. If you use something like this in some sort of profiler you will get results that make small fast methods appear very expensive. I.e. a ByteBuffer.get() is likely to execute at least 10 times faster than your measuring code. Together with the distortion due to limited JIT compiling when JVMTI is active such methods can easily appear 100 times heavier in the collected data than they are under normal circumstances. The only way to get somewhat usable data of the execution time share of methods is to use sampling.

Upvotes: 5

Related Questions