Get information about your memory and CPU usage in PHP

Here We’ll discuss about how to get information about your memory usage in PHP, It’ll help you optimize your script, You must have aware about which script of your’s taking too much time to execute, Otherwise it’ll kill server memory and you may have to face server down time issue.
PHP has a garbage collector and a pretty complex memory manager. The amount of memory being used by your script. can go up and down during the execution of a script.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.



See example.

echo "Initial Memory uses : ".memory_get_usage()." bytes \n";
// Initial Memory uses : 321420 bytes
 
// Let's create some function to use up some memory
for ($count = 0; $count < 100000; $count++) {
    $array []= base64_decode($count);
}
 
for ($count = 0; $count < 100000; $count++) {
    unset($array[$i]);
}
 echo "Final Memory : ".memory_get_usage()." bytes \n";
//Final Memory :: 871015 bytes
 
echo "Peak: ".memory_get_peak_usage()." bytes \n";
//Peak: 13483071 bytes



CPU Usage Information

For getting CPU uses you can simply use getrusage() function in php It’ll return lot’s of CPU uses variables which help you to determine whats sources uses too much CPU resources.

print_r(getrusage());
/* Output: 
Array
(
    [ru_oublock] => 0
    [ru_inblock] => 0
    [ru_msgsnd] => 2
    [ru_msgrcv] => 3
    [ru_maxrss] => 12692
    [ru_ixrss] => 764
    [ru_idrss] => 3864
    [ru_minflt] => 94
    [ru_majflt] => 0
    [ru_nsignals] => 1
    [ru_nvcsw] => 67
    [ru_nivcsw] => 4
    [ru_nswap] => 0
    [ru_utime.tv_usec] => 0
    [ru_utime.tv_sec] => 0
    [ru_stime.tv_usec] => 6269
    [ru_stime.tv_sec] => 0
) 
*/
Posted in PHP