How can I get the CPU and Memory useage

前端 未结 4 1400
一整个雨季
一整个雨季 2020-12-16 05:51

I want to know the memory and CPU usage in php, because I\'m using cronejobs sometimes the CPU is overloaded so in this case I don\'t wan to start more process, I just want

4条回答
  •  暖寄归人
    2020-12-16 06:49

    I recently have some issue to get CPU load and i feel like sharing it .

    Here was my solution witch help me out :

    My situation :

    I've use Zend Framework 1.2 to build monitoring application and i want to get cpu load and show it on the page . after doing some research i found out i could use COM Object and query the Win OS with wmi so i put these code to my init function :

        /* Initialize action controller here */
        $this->wmi = new COM('winmgmts:{impersonationLevel=impersonate}//./root/cimv2');
    
        if (!is_object($this->wmi)) {
            throw new GetInfoException('This needs access to WMI. Please enable DCOM in php.ini and allow the current user to access the WMI DCOM object.');
        }
    
    • You could use it anywhere you want , i have use it in the init function beacuse of Zend structure .

    And i added an Action and an function to use that wmi and get cpu load any time i want by calling that function .

    public function cpuloadAction()
    {
        echo json_encode($this->getLoad());
        exit();
    }
    
    private function getLoad() {
    
        // Time?
        if (!empty($this->settings['timer']))
            $t = new LinfoTimerStart('Load Averages');
    
        $load = array();
        foreach ($this->wmi->ExecQuery("SELECT LoadPercentage FROM Win32_Processor") as $cpu) {
            $load[] = $cpu->LoadPercentage;
        }
        //return round(array_sum($load) / count($load), 2) . "%";
        return (int)round(array_sum($load) / count($load), 2);
    }
    
    • beacuse i what real time data i put these code in a function Otherwise you could write it in single non Object Oriented PHP file.

    Hope it help .

提交回复
热议问题