Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

44
LINES

< > BotCompany Repo | #1019502 // oshi_calcProcessCPUUsage_v2 - better handling of deleted processes

JavaX fragment (include)

1  
scope oshi_calcProcessCPUUsage_v2.
2  
3  
sclass #Data {
4  
  long cpuTime, timestamp;
5  
  OSProcess process;
6  
}
7  
8  
// key: pid
9  
static Map<Int, Data> #map = synchroMap();
10  
11  
svoid _onLoad_oshi_calcProcessCPUUsage_v2 {
12  
  ownResource(vmBus_onMessage('osProcesses, voidfunc(L processes) {
13  
    Set<Int> keep = asHashSet(collectMethod(processes, 'getProcessID));
14  
    for (Iterator<Int> it = map.keySet().iterator(); it.hasNext(); ) {
15  
      Int pid = it.next();
16  
      if (!keep.contains(pid)) {
17  
        Data data = map.get(pid);
18  
        print("Lost process: [" + pid + "] " + data.process.getName());
19  
        it.remove();
20  
      }
21  
    }
22  
  }));
23  
}
24  
25  
// call this in proper interval (1 to 3 seconds) to work properly
26  
static double oshi_calcProcessCPUUsage_v2(OSProcess p) {
27  
  if (p == null) ret 0;
28  
  int pid = p.getProcessID();
29  
  Data data = map.get(pid);
30  
  if (data == null)
31  
    map.put(pid, data = nu(Data, process := p));
32  
33  
  long cpuTime = p.getKernelTime() + p.getUserTime();
34  
35  
  double result = 0;
36  
  long now = sysNow();
37  
  if (data.timestamp != 0)
38  
		result = percentRatio(cpuTime-data.cpuTime, now-data.timestamp);
39  
  data.timestamp = now;
40  
	data.cpuTime = cpuTime;
41  
	ret result;
42  
}
43  
44  
end scope

Author comment

Began life as a copy of #1019497

download  show line numbers  debug dex  old transpilations   

Travelled to 12 computer(s): bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, irmadwmeruwu, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1019502
Snippet name: oshi_calcProcessCPUUsage_v2 - better handling of deleted processes
Eternal ID of this version: #1019502/5
Text MD5: 2e22331ef7f7e5b0f68314c4aa4d2801
Author: stefan
Category: javax / os
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2018-11-10 22:52:41
Source code size: 1209 bytes / 44 lines
Pitched / IR pitched: No / No
Views / Downloads: 292 / 334
Version history: 4 change(s)
Referenced in: [show references]