Idle percentage of CPU and memory for the current system

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.