lime icon

Phosphorus and Lime

A Developer's Broadsheet

This blog has been deprecated. Please visit my new blog at klenwell.com/press.
PHP: Memory Usage Script
The following function can give you an idea of how much memory your script is using. It's based off a script found on the php.net site.

function memory_get_usage($echo=0)
{
$mb_usage = ''; // return

static $last_measure = 0;

$_OUT = array();

// Windows (requires tasklist.exe in C:\WINDOWS\system32)
// to download: http://www.computerhope.com/download/winxp.htm
if ( substr(PHP_OS,0,3) == 'WIN' )
{
exec( 'tasklist /FI "PID eq ' . getmypid() . '" /FO LIST', $_OUT );
if ( isset($_OUT[5]) )
{
$usage = preg_replace( '/[\D]/', '', $_OUT[5] ) * 1024;
$mb_usage = round(($usage / 1024 / 1024), 3);
}
else
{
trigger_error('tasklist failed to exec');
}
}

// Unix
else
{
$pid = getmypid();
exec("ps -eo%mem,rss,pid | grep $pid", $_OUT);
$output = explode(" ", $_OUT[0]);
$usage = $_OUT[1] * 1024;
$mb_usage = round(($usage / 1024 / 1024), 3);
}

if ( !empty($last_measure) && $echo )
{
$m3m = $mb_usage - $last_measure;
$m3k = $m3m * 1000;
echo "<pre style='color:#c33;'>memory usage: $last_measure -> $mb_usage | difference: $m3m MB, $m3k KB</pre>";
}
$last_measure = $mb_usage;

if ( $echo ) echo "<pre>mem usage in MB: <b>$mb_usage</b></pre>";
return $mb_usage;
}


Find a test script in the Klenwell code repository: test.mem_usage.php

Labels: