ThreadMXBean.getThreadCpuTime () includes only time spent in the RUNNABLE state, but note that the way this value is calculated is platform dependent.
Here's a program that shows that getThreadCpuTime () only covers the time when the thread is actually doing something:
import java.lang.management.*; public class Test implements Runnable { public static void main(String[] args) throws Exception { long time = System.nanoTime(); Test test = new Test(); synchronized (test) { new Thread(test).start(); while (test.cpu == -1) { test.wait(); } } System.out.println("time: " + (System.nanoTime() - time)); System.out.println("cpu: " + test.cpu); } private long cpu = -1; public synchronized void run() { try { ThreadMXBean thread = ManagementFactory.getThreadMXBean(); long cpu = thread.getCurrentThreadCpuTime(); Thread.sleep(300); long time = System.nanoTime(); while (System.nanoTime() - time < 700000000); this.cpu = thread.getCurrentThreadCpuTime() - cpu; } catch (InterruptedException _) {} finally { notify(); } } }
petithug
source share