Knowledge base‎ > ‎

Profiling Java application: measuring real CPU time

posted Apr 20, 2010, 5:26 AM by Szabolcs Szádeczky-Kardoss   [ updated Apr 22, 2010, 1:57 AM by István Soós ]
When profiling applications, it is always important to measure the time as precise as it can be, and the old way was to measure the system clock with increasing granularity, while in the meantime we have received access to a more precise, thread-specific clock.

In the old-fashioned way, we have two methods to measure the system clock:
  • System.currentTimeMillis()
  • System.nanoTime()
Both method depend on the operation system's internal clock API, so there is no guarantee on the granularity of the clock, however nanoTime tends to be more precise - as you would expect. The difference between the two is that nanoTime does not relates to the date information anyhow (no counting of milliseconds since 1970 or so). Measuring a single-threaded application, with not much multitasking in the background (e.g. "nobody shall touch the machine while I'll do the benchmark") produces good results.
However if the thread or process context is switched by the operation system (because the user moves the mouse or something else steals any CPU time or IO interruption), measuring the system clock will always result larger number than it actually consumed. Of course, if you repeat the measurements and calculate the supremum of the numbers, it will give you good estimates, but that will always be just an estimate.

On the other hand, the Java platform now provides easy access to an other clock: the thread's own CPU time counter, which can compute the CPU time spent in the actual thread. This is more precise in the regard that thread and process context switches are not measured, only the time when the thread is active. Although the usual Thread and System classes don't provide such methods, Sun's JVM provides a simple way to achieve it:
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
long time = threadMXBean.getCurrentThreadCpuTime();
Simple, isn't it? Of course you can check other methods on this MXBean, but it gives the basic idea behind precise CPU time measurements.

published: 2009-08-24, a:István, y:2009, l:java, l:profiling