The answer to this question was an article about how to measure processor load, based on the above functions - this is how you managed to solve the problem of controlling the load on the processor
function onRequestStart() { $dat = getrusage(); define('PHP_TUSAGE', microtime(true)); define('PHP_RUSAGE', $dat["ru_utime.tv_sec"]*1e6+$dat["ru_utime.tv_usec"]); } function getCpuUsage() { $dat = getrusage(); $dat["ru_utime.tv_usec"] = ($dat["ru_utime.tv_sec"]*1e6 + $dat["ru_utime.tv_usec"]) - PHP_RUSAGE; $time = (microtime(true) - PHP_TUSAGE) * 1000000; // cpu per request if($time > 0) { $cpu = sprintf("%01.2f", ($dat["ru_utime.tv_usec"] / $time) * 100); } else { $cpu = '0.00'; } return $cpu; } $start=time(); onRequestStart();//запускается в начале скрипта $a=1000000; $size=10000000; $counter=0; $timeout=100000; for($i=0;$i<=$size;$i++){ $a+=100; if(getCpuUsage()>80){//если загрузка процессора достигла 80% погружаем процесс на одну сотую секунды в сон usleep($timeout); ++$counter; } } $end=time()-$start; echo 'Спал '.$timeout*$counter/1000000 .' секунд; ушло времени '.$end.' c'; gc_disable(); //чистка мусора из памяти сервера
here are the test results
$timeout=1000000; //Спал 8 секунд; ушло времени 48 c - результатов не дало - процессор загружался на 100% $timeout=100000; //Спал 7.5 секунд; ушло времени 46 c $timeout=10000; //Спал 7.95 секунд; ушло времени 48 c $timeout=1000; //Спал 7.888 секунд; ушло времени 49 c $timeout=100; //Спал 5.3308 секунд; ушло времени 50 c $timeout=10; //Спал 1.18124 секунд; ушло времени 47 c $timeout=1; //Спал 0.152863 секунд; ушло времени 50 c
in all cases except the first, the processor load did not exceed 85% of the htop results - perhaps this is due to the fact that htop is updated once a second
I also noticed that with a decrease in sleep time, the number of falling asleep increases from 3,500 to 250,000, with a total of 10,000,000 cycles