Tracking Memory Usage in PHP

前端 未结 4 979
无人及你
无人及你 2020-11-29 02:15

I\'m trying to track the memory usage of a script that processes URLs. The basic idea is to check that there\'s a reasonable buffer before adding another URL to a cURL multi

4条回答
  •  天涯浪人
    2020-11-29 03:00

    I also assume memory_get_usage() is safe but I guess you can compare both methods and decide for yourself, here is a function that parses the system calls:

    function Memory_Usage($decimals = 2)
    {
        $result = 0;
    
        if (function_exists('memory_get_usage'))
        {
            $result = memory_get_usage() / 1024;
        }
    
        else
        {
            if (function_exists('exec'))
            {
                $output = array();
    
                if (substr(strtoupper(PHP_OS), 0, 3) == 'WIN')
                {
                    exec('tasklist /FI "PID eq ' . getmypid() . '" /FO LIST', $output);
    
                    $result = preg_replace('/[\D]/', '', $output[5]);
                }
    
                else
                {
                    exec('ps -eo%mem,rss,pid | grep ' . getmypid(), $output);
    
                    $output = explode('  ', $output[0]);
    
                    $result = $output[1];
                }
            }
        }
    
        return number_format(intval($result) / 1024, $decimals, '.', '');
    }
    

提交回复
热议问题