program linux_cpu; // https://www.idnt.net/en-GB/kb/941772
{$MODE OBJFPC}{$H+}
uses sysutils;
function givehead:string;
var
head: string absolute givehead;
procstatfile:Text;
oldfilemode:longint;
begin
head:='';
oldfilemode:=FileMode;
Filemode:=fmOpenread;
Assign(procstatfile,'/proc/stat');
Reset(procstatfile);
ReadLn(procstatfile,head);
Close(procstatfile);
FileMode:=oldfilemode
end;
procedure cpu_utilization(times:integer=100);
type
tcpu_values=array[1..9]of longint;
var
i,n:integer;
timesleft:boolean;
head:string;
cpu_now,
cpu_last:tcpu_values;
cpu_sum,
cpu_last_sum,
cpu_delta,
cpu_idle,
cpu_used:longint;
cpu_usage:single;
begin
n:=0;
timesleft:=n<times;
cpu_last:=default(tcpu_values);
cpu_last_sum:=0;
while timesleft do
begin
// loop timesleft
inc(n);
timesleft:=n<times;
// Get the first line with aggregate of all CPUs
head:=givehead;
// Get all columns but skip first (which is the "cpu" string)
head:=stringreplace(head,'cpu','',[]);
readstr(head,cpu_now[1],cpu_now[2],cpu_now[3],cpu_now[4],cpu_now[5],cpu_now[6],cpu_now[7],cpu_now[8],cpu_now[9]);
// Sum cpu_sum
cpu_sum:=0;
for i:=low(cpu_now)to high(cpu_now)do
cpu_sum:=cpu_sum+cpu_now[i];
// Get the delta between two reads
cpu_delta:=cpu_sum-cpu_last_sum;
// Get the idle time Delta
cpu_idle:=cpu_now[4]-cpu_last[4];
// Calc time spent working
cpu_used:=cpu_delta-cpu_idle;
// Calc percentage
cpu_usage:=100*cpu_used/cpu_delta;
// Keep this as last for our next read
cpu_last:=cpu_now;
cpu_last_sum:=cpu_sum;
writeln('CPU usage at ',cpu_usage:3:2,'%');
// wait a second before the next read
sleep(1*1000)
end
end;
begin
cpu_utilization(10)
end.