if your program has no I/O, and there's nothing else running on the machine at the same time, then for most purposes you can assume CPU time == real time
If the program in multi-threaded, the CPU time gives the "total" time spent by each CPU/core. So even if the real/wall time is 1s, it's quite possible that the CPU time might be 4s for a multi-threaded CPU intensive code.
@corol
There are two techniques which you can put to use:
- Use the JMX API to get an approximate CPU time for all threads
- Use the
time
unix command when executing your Java process
For (1), you can have a look at the Thread MBean. Here is a small snippet:
public class TestIt {
public static void main(String[] args) throws Exception {
int numThreads = 5;
long start = System.currentTimeMillis();
for (int i = 0; i < numThreads; ++i) {
new MyThread().start();
}
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
long[] allThreadIds = threadMXBean.getAllThreadIds();
System.out.println("Total JVM Thread count: " + allThreadIds.length);
long nano = 0;
for (long id : allThreadIds) {
nano += threadMXBean.getThreadCpuTime(id);
}
System.out.printf("Total cpu time: %s ms; real time: %s", nano / 1E6, (System.currentTimeMillis() - start));
}
}
class MyThread extends Thread {
public void run() {
int sum = 0;
for (int i = 0; i < 1000000; ++i) {
sum += i;
}
sum = sum + 1;
}
}
Of course, this snippet has problems of its own. This code won't consider …