So now you have:
- The elapsed wall clock time (this period's time, minus last period's time) Call this X
- The elapsed process cpu time (this period's time, minus last period's time) Call this Y
- The number of CPUs. Call this C
The percent utilization will be Y / (X x C) * 100
import java.lang.management.*;
import java.util.concurrent.*;
osx = ManagementFactory.getOperatingSystemMXBean();
cores = osx.getAvailableProcessors(); // Factorial to keep the process busy so we can see some actual activity
factorial = { n -> int fact = 1; int i = 1; while(i <= n) { i++; fact *= i; } return fact; }
long elapsedTime = -1, startTime = -1; long elapsedCpu = -1, startCpu = -1;;
for(i in 0..20) { startTime = System.nanoTime(); startCpu = osx.getProcessCpuTime(); CountDownLatch latch = new CountDownLatch(cores); for(x in 1..cores) { Thread.startDaemon() { factorial(1000000); latch.countDown(); } } latch.await(); elapsedTime = System.nanoTime()-startTime; elapsedCpu = osx.getProcessCpuTime()-startCpu; percUsage = (elapsedCpu / (elapsedTime* cores)) *100; println "Percent Usage:$percUsage %"; }