Imagine that we have a PHP page a resource-intensive, so we need to check the current CPU and memory idle percentage of the system every time we execute the code in page A.
We can use the following functions to solve this problem
12345678910111213141516171819202122232425262728293031 |
Get idle percent of Cpu function Get_cpufree () {$cmd = "Top-n 1-b-D 0.1 | grep ' CPU ';//Call the top command and grep command $lastline = EXEC ($cmd, $ou Tput); Preg_match ('/(\s+)%id/', $lastline, $matches);//Regular expression Gets the percentage of CPU idle $cpufree = $matches [1];return $cpufree;} Get memory idle percent function Get_memfree () {$cmd = ' free-m ';//Call the free command $lastline = EXEC ($cmd, $output); Preg_match ('/mem:\s + (\d+)/', $output [1], $matches); $memtotal = $matches [1];p Reg_match ('/(\d+) $/', $output [2], $matches); $memfree = $ Matches[1]*100.0/$memtotal; return $memfree;} Gets the current number of processes for a program function Get_proc_count ($name) {$cmd = "ps-e";//Call PS Command $output = shell_exec ($cmd); $result = Substr_ Count ($output, ". $name); return $result;} |
For example, when the CPU idle rate is less than 30%, we delay page a execution:
1234567 |
$cpufree = Get_cpufree (); while ($cpufree <30) {//wait for 0.1 secondsusleep (0.1*1000000); $cpufree = Get_cpufree ();}; |
Idle percentage of CPU and memory for the current system