scope oshi_calcProcessCPUUsage_v2. sclass #Data { long cpuTime, timestamp; OSProcess process; } // key: pid static Map #map = synchroMap(); svoid _onLoad_oshi_calcProcessCPUUsage_v2 { ownResource(vmBus_onMessage('osProcesses, voidfunc(L processes) { Set keep = asHashSet(collectMethod(processes, 'getProcessID)); for (Iterator it = map.keySet().iterator(); it.hasNext(); ) { Int pid = it.next(); if (!keep.contains(pid)) { Data data = map.get(pid); print("Lost process: [" + pid + "] " + data.process.getName()); it.remove(); } } })); } // call this in proper interval (1 to 3 seconds) to work properly static double oshi_calcProcessCPUUsage_v2(OSProcess p) { if (p == null) ret 0; int pid = p.getProcessID(); Data data = map.get(pid); if (data == null) map.put(pid, data = nu(Data, process := p)); long cpuTime = p.getKernelTime() + p.getUserTime(); double result = 0; long now = sysNow(); if (data.timestamp != 0) result = percentRatio(cpuTime-data.cpuTime, now-data.timestamp); data.timestamp = now; data.cpuTime = cpuTime; ret result; } end scope