Wednesday, September 3, 2008

Performance Measurement in Java?

Yes its another post, i wanted to keep the individual posts regarding only one topic/issue.

So in this post what I was thinking about is Performance timing in Java. What is the best way to Measure Time / Performance in Java or in other which methods are appropriate when it comes to analysis and comparisons.

The first method i came across is the most basic and the one i've come across before which is simply the currenttime from System i.e
long time = System.currentTimeMillis();
time = System.currentTimeMillis() - time;
System.out.println("Operation took: " + time + "ms");
The method returns time in milliseconds since Jan 1 1970. From my understanding though this measures "elapsed time" so it can give variable results when dealing with multitasking as the thread may get swapped out for something else between the two time calls.

From this discovery i found the other method which measures CPU time consumed by the current thread.

ThreadMXBean mx;
if( &&{
long time = mx.getCurrentThreadCpuTime();
time = mx.getCurrentThreadCputTime() - time;
This method measures how long the thread was running on CPU , and thus should give you a value which is independent of whatever multitasking your system is doing (which can vary elapsed time) when the test runs.

When i ran my earlier tests i used both methods of measurement and for some operations they both returned similar/same values whilst with other operations the results were significantly different.

So which is the best to use? I'm still not sure, i think the less variability that the thread time gives is an advantage but i will probably need to look into it more to see if this is the appropriate way to measure time.

No comments: