<?php if(!dl("ffi")) throw new Exception('无法加载 FFI 扩展。');
function GetSystemTimes()
{
static $Kernel32;
$Kernel32??=FFI::cdef(<<<'IDL'
bool GetSystemTimes(long long *IdleTime, long long *KernelTime, long long *UserTime);
int GetLastError();
IDL, 'Kernel32.dll');
$IdleTime = FFI::new('long long');
$KernelTime = FFI::new('long long'); $UserTime = FFI::new('long long');
if($Kernel32->GetSystemTimes(FFI::addr($IdleTime), FFI::addr($KernelTime), FFI::addr($UserTime)))
return [
'Idle' =>$IdleTime ->cdata,
'Kernel' =>$KernelTime ->cdata, 'User' =>$UserTime ->cdata,
];
return [];
}
function GetSystemTimesDelta()
{
static $Last=null;
static $Delta=[0,1];
$Times=GetSystemTimes();
$Last??=$Times;
$Idle =$Times['Idle' ]-$Last['Idle' ];
$All =$Times['Kernel' ]-$Last['Kernel' ]+ $Times['User' ]-$Last['User' ];
if($All>1_000_000) {
$Delta=[$Idle, $All];
$Last=$Times;
}
return $Delta;
}
function ProcessorLoad()
{
static $Load=0;
[$Idle, $All]=GetSystemTimesDelta();
if($All>0.0)
$Load=1-$Idle/$All;
return $Load;
}
function KbHit()
{
Static $Sys;
$Sys??=FFI::cdef('bool _kbhit();', 'msvcrt.dll');
return $Sys->_kbhit();
}
while(!KbHit())
{
echo str_pad((string)round(ProcessorLoad()*100), 3, ' ', STR_PAD_LEFT), "%\n";
sleep(1);
}
?>