lime icon

Phosphorus and Lime

A Developer's Broadsheet

This blog has been deprecated. Please visit my new blog at klenwell.com/press.
PHP: Get Memory Usage
In the final stages of setting up hosting service. Going with a shared host to start and really trying to get a grasp of how efficiently my scripts run, how well they scale up, and how many users they can accommodate before we'll need to step up to VPS or dedicated hosting.

I adapted the following script from the PHP site. It needs to be directly included so I've compressed the formatting as much as possible:

function inmem() {
if ( substr(PHP_OS,0,3) == 'WIN') {
exec( 'tasklist /FI "PID eq ' . getmypid() . '" /FO LIST', $output );
$mb_usage = round(preg_replace( '/[\D]/', '', $output[5] ) / 1024, 3); }
else {
$pid = getmypid();
exec("ps -eo%mem,rss,pid | grep $pid", $output);
$output = explode(" ", $output[0]);
$mb_usage = round(($output[1] / 1024), 3); }
echo "<h4>current script MB usage : $mb_usage</h4>"; } // end Fx

inmem();


Running it on my current script on my local laptop server, I find it jumps from 28 MB at the beginning of my script, before my codebase has loaded, 34 MB by the end -- which as far as I can tell at this point is not too bad.

keywords: php, server, resources, usage, optimization
started thread on this topic on comp.lang.php
In your script I would add a trim around the $output in this line:

$output = explode(" ",trim(output[0]));

because in my testing the server had a space at the beginning