Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get server CPU usage and RAM usage with php? [duplicate]

Tags:

php

cpu-usage

I want to get server CPU and RAM usage using php. The script should work on windows and linux.

How would I do that?

like image 320
Mehdi Homeyli Avatar asked Apr 08 '14 22:04

Mehdi Homeyli


People also ask

How can I get CPU and memory usage in PHP?

To get the current memory usage, we can use the memory_get_usage() function, and to get the highest amount of memory used at any point, we can use the memory_get_peak_usage() function.

How do I check my CPU and RAM on my server?

Using the Task Manager Press the Windows key , type task manager, and press Enter . In the window that appears, click the Performance tab. On the Performance tab, a list of hardware devices is displayed on the left side.

How do I monitor PHP memory usage?

The memory_get_usage function can be used to track the memory usage. The 'malloc' function is not used for every block required, instead a big chunk of system memory is allocated and the environment variable is changed and managed internally. The above mentioned memory usage can be tracked using memory_get_usage().


1 Answers

The first function will return the Server Memory Usage:

function get_server_memory_usage(){

    $free = shell_exec('free');
    $free = (string)trim($free);
    $free_arr = explode("\n", $free);
    $mem = explode(" ", $free_arr[1]);
    $mem = array_filter($mem);
    $mem = array_merge($mem);
    $memory_usage = $mem[2]/$mem[1]*100;

    return $memory_usage;
}

This function will return the Server CPU Usage:

function get_server_cpu_usage(){

    $load = sys_getloadavg();
    return $load[0];

}
like image 161
Snoobih Avatar answered Oct 22 '22 09:10

Snoobih