!747 !pcall { m { static Map idToThread; static new WeakHashMap infoMap; static class Info { long cpuTime, measuredWhen; // all in milliseconds double percentage; // percentage of CPU used } static ThreadMXBean mx; static boolean cpuTimeSupported; static double totalPercentage; // all threads combined p { mx = ManagementFactory.getThreadMXBean(); cpuTimeSupported = mx.isThreadCpuTimeSupported(); if (!cpuTimeSupported) fail("No CPU time info available on platform."); while (true) { pcall { monitor(); printMostActiveThread(); } sleepSeconds(1); } } static void monitor() { L threads = getAllThreads(); new WeakHashMap newInfoMap; totalPercentage = 0; for (Thread t : threads) { Info info = infoMap.get(t); if (info == null) info = new Info; newInfoMap.put(t, info); long nano = 0; pcall { nano = mx.getThreadCpuTime(t.getId()); } long measured = now(); long ms = nano/1000000; if (info.measuredWhen != 0) { long elapsed = measured - info.measuredWhen; long used = ms-info.cpuTime; info.percentage = Math.max(0, Math.min(100, used*100.0/elapsed)); totalPercentage += info.percentage; } info.measuredWhen = measured; info.cpuTime = ms; } infoMap = newInfoMap; } static void printMostActiveThread() { Thread mostActive = null; double highest = 0.0; for (Map.Entry e : infoMap.entrySet()) { Thread t = e.getKey(); Info info = e.getValue(); if (mostActive == null || info.percentage > highest) { mostActive = t; highest = info.percentage; } } if (mostActive == null) print("No info"); else print("Total CPU used by this VM: " + formatDouble(totalPercentage, 1) + "%. Most active thread: " + mostActive.getName() + " (" + formatDouble(highest, 1) + "% CPU)"); } static L getAllThreads() { ThreadGroup rootGroup = Thread.currentThread().getThreadGroup(); ThreadGroup parentGroup; while ( ( parentGroup = rootGroup.getParent() ) != null ) rootGroup = parentGroup; Thread[] threads = new Thread[rootGroup.activeCount()]; int n; while ((n = rootGroup.enumerate(threads, true)) == threads.length) threads = new Thread[threads.length*2]; L l = new ArrayList(n); for (int i = 0; i < n; i++) l.add(threads[i]); ret l; } }