Repository navigation
Expand file tree
/
Copy pathLightCore.ProcessCpuMonitor.pas
More file actions
467 lines (398 loc) · 15.3 KB
/
Copy pathLightCore.ProcessCpuMonitor.pas
File metadata and controls
467 lines (398 loc) · 15.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
UNIT LightCore.ProcessCpuMonitor;
{=============================================================================================================
2026.11.02
www.GabrielMoraru.com
--------------------------------------------------------------------------------------------------------------
Enumerates all running processes and returns the top-N by CPU usage and RAM consumption.
Designed for overlay display (mini Task Manager on the desktop).
CPU% is smoothed via exponential moving average (EMA) to prevent the process list
from jumping around between updates. The smoothing factor (ALPHA) controls how fast
the display reacts: lower = slower/smoother, higher = faster/jumpier.
Usage:
var Mon: TProcessListMonitor;
Mon:= TProcessListMonitor.Create;
try
Mon.Sample; // First call establishes baseline (CPU deltas need two samples)
Sleep(1500);
Mon.Sample; // Now TopCpu is populated
for i:= 0 to Mon.TopCpuCount-1 do
WriteLn(Mon.GetTopCpu(i).Name, ' ', Mon.GetTopCpu(i).CpuPercent:5:1, '%');
for i:= 0 to Mon.TopRamCount-1 do
WriteLn(Mon.GetTopRam(i).Name, ' ', Mon.GetTopRam(i).WorkingSetBytes);
finally
FreeAndNil(Mon);
end;
Notes:
- Processes with the same exe name are aggregated (all chrome.exe instances summed)
- PID reuse is detected by name change (delta reset to 0)
- Protected/system processes that cannot be opened are silently skipped
- First Sample() call populates RAM but not CPU (needs two samples for delta)
- CPU% values are smoothed over time; processes not seen for several samples fade out
- CPU% = the CPU cycles of each process (QueryProcessCycleTime) divided by the ticks of the time-stamp counter in the same interval. GetProcessTimes is not used: on Windows 11 it reads 0 for seconds at a time for work done in short bursts. The measurements and sources: the header of LightCore.CpuUsageProcess.pas.
Also see:
* LightCore.CpuUsageProcess.pas - per-process CPU monitor (single process)
* LightVcl.Common.CpuMonitor.pas - system-wide CPU monitor
* LightCore.Process.pas - process enumeration utilities
Sample is the only routine that reads the system, and it reads it through Windows calls (the process snapshot, OpenProcess, QueryProcessCycleTime, the time-stamp counter, GetProcessMemoryInfo); every other routine works only on what Sample stored, and GetTopCpu, GetTopRam, TopCpuCount and TopRamCount return measured values. So the whole unit is declared inside a MSWINDOWS conditional - interface and implementation both. Off Windows a TopCpuCount of 0 would read as "no process uses the CPU", which is a silent wrong answer, so a call written in an Android, macOS or iOS build fails to compile instead, and this unit compiles empty there.
=============================================================================================================}
INTERFACE
{$IFDEF MSWINDOWS}
USES
Winapi.Windows;
CONST
TOP_N = 5;
{ EMA smoothing factor: 0.25 means 25% weight on new sample, 75% on history.
At 1.5s sample interval this gives ~6 second effective averaging window.
Lower value = smoother/slower, higher = faster/jumpier. }
ALPHA = 0.25;
{ Processes with smoothed CPU% below this threshold are pruned from the smoothing table }
PRUNE_THRESHOLD = 0.01;
TYPE
RProcessInfo = record
Name: string; { Process name without .exe }
CpuPercent: Single; { 0..100, normalized to total CPU capacity (all cores) }
WorkingSetBytes: Int64;
end;
RPidSample = record
PID: DWORD;
Name: string;
Cycles: UInt64; { QueryProcessCycleTime }
end;
TPidSamples = array of RPidSample;
TProcessListMonitor = class
private
type
RAggregated = record
Name: string;
CpuPercent: Single;
WorkingSetBytes: Int64;
end;
{ Smoothed CPU% per process name, persists across Sample() calls }
RSmoothed = record
Name: string;
SmoothedCpu: Single;
end;
var
FPrevSamples: TPidSamples;
FPrevSampleCount: Integer;
FPrevStamp: UInt64; { ReadTimeStampCounter at the previous Sample. 0 = no Sample yet }
FTopCpu: array[0..TOP_N-1] of RProcessInfo;
FTopRam: array[0..TOP_N-1] of RProcessInfo;
FTopCpuCount: Integer; { 0..TOP_N, actual entries filled }
FTopRamCount: Integer;
{ EMA smoothing table for CPU% }
FSmoothed: array of RSmoothed;
FSmoothedCount: Integer;
function FindPrevSample(PID: DWORD; CONST Name: string): Integer;
function FindSmoothed(CONST Name: string): Integer;
procedure UpdateSmoothed(CONST Name: string; RawCpu: Single);
procedure DecayUnseen(CONST Agg: array of RAggregated; AggCount: Integer);
procedure PruneSmoothed;
public
ExcludeName: string; { Process name to hide from results (e.g. 'MyApp.exe'). Case-insensitive. Compared with and without .exe extension. }
procedure Sample;
function GetTopCpu(Index: Integer): RProcessInfo;
function GetTopRam(Index: Integer): RProcessInfo;
property TopCpuCount: Integer read FTopCpuCount;
property TopRamCount: Integer read FTopRamCount;
end;
{$ENDIF}
IMPLEMENTATION
{$IFDEF MSWINDOWS}
USES
System.SysUtils, System.Math, TlHelp32, Winapi.PsAPI,
LightCore.CpuUsageProcess;
CONST
{ Vista+ constant. Declared here in case Winapi.Windows header is missing it. }
PROCESS_QUERY_LIMITED_INFORMATION_FLAG = $1000;
{ Look up a PID in the previous sample array.
Returns index or -1 if not found or if name changed (PID reuse). }
function TProcessListMonitor.FindPrevSample(PID: DWORD; CONST Name: string): Integer;
VAR i: Integer;
begin
for i:= 0 to FPrevSampleCount - 1 do
if (FPrevSamples[i].PID = PID) AND SameText(FPrevSamples[i].Name, Name)
then EXIT(i);
Result:= -1;
end;
{ Find a process name in the smoothing table. Returns index or -1. }
function TProcessListMonitor.FindSmoothed(CONST Name: string): Integer;
VAR i: Integer;
begin
for i:= 0 to FSmoothedCount - 1 do
if SameText(FSmoothed[i].Name, Name)
then EXIT(i);
Result:= -1;
end;
{ Update or insert an EMA-smoothed CPU% entry for the given process name. }
procedure TProcessListMonitor.UpdateSmoothed(CONST Name: string; RawCpu: Single);
VAR Idx: Integer;
begin
Idx:= FindSmoothed(Name);
if Idx >= 0 then
{ Blend new value into existing average }
FSmoothed[Idx].SmoothedCpu:= FSmoothed[Idx].SmoothedCpu * (1 - ALPHA) + RawCpu * ALPHA
else
begin
{ New entry: start with raw value }
if FSmoothedCount >= Length(FSmoothed)
then SetLength(FSmoothed, FSmoothedCount + 32);
FSmoothed[FSmoothedCount].Name:= Name;
FSmoothed[FSmoothedCount].SmoothedCpu:= RawCpu;
Inc(FSmoothedCount);
end;
end;
{ Decay smoothed values for processes NOT seen in the current aggregation.
This makes processes that stopped using CPU fade out gracefully. }
procedure TProcessListMonitor.DecayUnseen(CONST Agg: array of RAggregated; AggCount: Integer);
VAR i, j: Integer;
Found: Boolean;
begin
for i:= 0 to FSmoothedCount - 1 do
begin
Found:= FALSE;
for j:= 0 to AggCount - 1 do
if SameText(FSmoothed[i].Name, Agg[j].Name) then
begin
Found:= TRUE;
Break;
end;
if NOT Found then
{ Process not running or has 0 CPU: decay toward zero }
FSmoothed[i].SmoothedCpu:= FSmoothed[i].SmoothedCpu * (1 - ALPHA);
end;
end;
{ Remove entries with negligible smoothed CPU% to prevent unbounded table growth. }
procedure TProcessListMonitor.PruneSmoothed;
VAR i: Integer;
begin
i:= 0;
while i < FSmoothedCount do
begin
if FSmoothed[i].SmoothedCpu < PRUNE_THRESHOLD then
begin
{ Move last entry into this slot }
FSmoothed[i]:= FSmoothed[FSmoothedCount - 1];
Dec(FSmoothedCount);
end
else
Inc(i);
end;
end;
{ Takes a snapshot of all running processes and computes top-N by CPU and RAM.
Algorithm:
1. Read the time-stamp counter, compute DeltaStamp from previous call
2. Enumerate all processes via CreateToolhelp32Snapshot
3. For each process: OpenProcess -> QueryProcessCycleTime (CPU) + GetProcessMemoryInfo (RAM)
4. CPU% is computed as delta of cycles since previous sample,
normalized to total CPU capacity: DeltaCycles / DeltaStamp / NumCPUs * 100
5. Aggregate all instances of the same exe name (sum CPU% and RAM)
6. Smooth CPU% via exponential moving average (EMA) for stable rankings
7. Partial selection sort to extract top-5 by smoothed CPU and top-5 by RAM
8. Store current PID times for the next delta computation }
procedure TProcessListMonitor.Sample;
VAR
SnapHandle: THandle;
ProcEntry: TProcessEntry32;
ProcHandle: THandle;
MemCounters: TProcessMemoryCounters;
ThisStamp, DeltaStamp, Cycles: UInt64;
CpuPct: Single;
NumCPUs: Integer;
HasPrev: Boolean;
PrevIdx, SmIdx: Integer;
{ Current sample storage }
CurSamples: TPidSamples;
CurCount: Integer;
{ Aggregation storage }
Agg: array of RAggregated;
AggCount: Integer;
function StripExe(CONST AName: string): string;
VAR Len: Integer;
begin
Result:= AName;
Len:= Length(Result);
if (Len > 4) AND SameText(Copy(Result, Len - 3, 4), '.exe')
then Result:= Copy(Result, 1, Len - 4);
end;
procedure AddToAggregation(CONST AName: string; ACpuPct: Single; AWorkingSet: Int64);
VAR j: Integer;
begin
{ Skip excluded process }
if (ExcludeName <> '') AND (SameText(AName, ExcludeName) OR SameText(StripExe(AName), ExcludeName))
then EXIT;
{ Search for existing entry with same name }
for j:= 0 to AggCount - 1 do
if SameText(Agg[j].Name, AName) then
begin
Agg[j].CpuPercent:= Agg[j].CpuPercent + ACpuPct;
Agg[j].WorkingSetBytes:= Agg[j].WorkingSetBytes + AWorkingSet;
EXIT;
end;
{ New entry }
if AggCount >= Length(Agg)
then SetLength(Agg, AggCount + 64);
Agg[AggCount].Name:= AName;
Agg[AggCount].CpuPercent:= ACpuPct;
Agg[AggCount].WorkingSetBytes:= AWorkingSet;
Inc(AggCount);
end;
procedure SortBySmoothedCpu;
VAR i, j, Best: Integer;
Tmp: RAggregated;
begin
{ Replace raw CPU% with smoothed values before sorting }
for i:= 0 to AggCount - 1 do
begin
SmIdx:= FindSmoothed(Agg[i].Name);
if SmIdx >= 0
then Agg[i].CpuPercent:= FSmoothed[SmIdx].SmoothedCpu;
end;
{ Partial selection sort - only need top TOP_N }
for i:= 0 to Min(TOP_N, AggCount) - 1 do
begin
Best:= i;
for j:= i + 1 to AggCount - 1 do
if Agg[j].CpuPercent > Agg[Best].CpuPercent
then Best:= j;
if Best <> i then
begin
Tmp:= Agg[i];
Agg[i]:= Agg[Best];
Agg[Best]:= Tmp;
end;
end;
end;
procedure SortByRam;
VAR i, j, Best: Integer;
Tmp: RAggregated;
begin
for i:= 0 to Min(TOP_N, AggCount) - 1 do
begin
Best:= i;
for j:= i + 1 to AggCount - 1 do
if Agg[j].WorkingSetBytes > Agg[Best].WorkingSetBytes
then Best:= j;
if Best <> i then
begin
Tmp:= Agg[i];
Agg[i]:= Agg[Best];
Agg[Best]:= Tmp;
end;
end;
end;
VAR
i, Count: Integer;
begin
ThisStamp:= ReadTimeStampCounter;
HasPrev:= (FPrevStamp > 0) AND (ThisStamp > FPrevStamp); { FALSE on the first call, and if the counter went backwards (the unsigned subtraction would wrap) }
if HasPrev
then DeltaStamp:= ThisStamp - FPrevStamp
else DeltaStamp:= 0;
NumCPUs:= CPUCount;
SnapHandle:= CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if SnapHandle = INVALID_HANDLE_VALUE then EXIT;
CurCount:= 0;
AggCount:= 0;
SetLength(CurSamples, 256);
SetLength(Agg, 128);
TRY
ProcEntry.dwSize:= SizeOf(ProcEntry);
if NOT Process32First(SnapHandle, ProcEntry) then EXIT;
REPEAT
{ Skip System Idle Process }
if ProcEntry.th32ProcessID = 0 then Continue;
ProcHandle:= OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION_FLAG, False, ProcEntry.th32ProcessID);
if ProcHandle = 0 then Continue;
TRY
CpuPct:= 0;
if NOT QueryProcessCycleTime(ProcHandle, Cycles)
then Cycles:= 0;
{ Compute CPU delta if we have a previous sample }
if HasPrev AND (Cycles > 0) then
begin
PrevIdx:= FindPrevSample(ProcEntry.th32ProcessID, ProcEntry.szExeFile);
if PrevIdx >= 0 then
begin
if Cycles > FPrevSamples[PrevIdx].Cycles
then CpuPct:= (Cycles - FPrevSamples[PrevIdx].Cycles) / DeltaStamp / NumCPUs * 100;
{ Clamp to reasonable range }
if CpuPct > 100 then CpuPct:= 100;
if CpuPct < 0 then CpuPct:= 0;
end;
end;
{ Query memory }
FillChar(MemCounters, SizeOf(MemCounters), 0);
MemCounters.cb:= SizeOf(MemCounters);
GetProcessMemoryInfo(ProcHandle, @MemCounters, SizeOf(MemCounters));
{ Store current sample for next delta computation }
if CurCount >= Length(CurSamples)
then SetLength(CurSamples, CurCount + 128);
CurSamples[CurCount].PID:= ProcEntry.th32ProcessID;
CurSamples[CurCount].Name:= ProcEntry.szExeFile;
CurSamples[CurCount].Cycles:= Cycles;
Inc(CurCount);
{ Aggregate by process name }
AddToAggregation(ProcEntry.szExeFile, CpuPct, Int64(MemCounters.WorkingSetSize));
FINALLY
CloseHandle(ProcHandle);
END;
UNTIL NOT Process32Next(SnapHandle, ProcEntry);
FINALLY
CloseHandle(SnapHandle);
END;
{ Store samples for next call }
FPrevStamp:= ThisStamp;
SetLength(CurSamples, CurCount);
FPrevSamples:= CurSamples;
FPrevSampleCount:= CurCount;
{ Update EMA smoothing for all aggregated processes }
if HasPrev then
begin
for i:= 0 to AggCount - 1 do
UpdateSmoothed(Agg[i].Name, Agg[i].CpuPercent);
DecayUnseen(Agg, AggCount);
PruneSmoothed;
end;
{ Fill TopCpu using smoothed CPU% values }
if HasPrev then
begin
SortBySmoothedCpu;
Count:= Min(TOP_N, AggCount);
FTopCpuCount:= 0;
for i:= 0 to Count - 1 do
if Agg[i].CpuPercent > 0 then
begin
FTopCpu[FTopCpuCount].Name:= StripExe(Agg[i].Name);
FTopCpu[FTopCpuCount].CpuPercent:= Agg[i].CpuPercent;
FTopCpu[FTopCpuCount].WorkingSetBytes:= Agg[i].WorkingSetBytes;
Inc(FTopCpuCount);
end;
end
else
FTopCpuCount:= 0; { First sample - no delta available }
{ Fill TopRam (RAM is instant, no smoothing needed) }
SortByRam;
Count:= Min(TOP_N, AggCount);
FTopRamCount:= 0;
for i:= 0 to Count - 1 do
if Agg[i].WorkingSetBytes > 0 then
begin
FTopRam[FTopRamCount].Name:= StripExe(Agg[i].Name);
FTopRam[FTopRamCount].CpuPercent:= Agg[i].CpuPercent;
FTopRam[FTopRamCount].WorkingSetBytes:= Agg[i].WorkingSetBytes;
Inc(FTopRamCount);
end;
end;
function TProcessListMonitor.GetTopCpu(Index: Integer): RProcessInfo;
begin
Assert((Index >= 0) AND (Index < FTopCpuCount), 'TopCpu index out of range');
Result:= FTopCpu[Index];
end;
function TProcessListMonitor.GetTopRam(Index: Integer): RProcessInfo;
begin
Assert((Index >= 0) AND (Index < FTopRamCount), 'TopRam index out of range');
Result:= FTopRam[Index];
end;
{$ENDIF}
end.