Skip to content

Debugging PHP memory consumption without memory_get_usage

April 22, 2009

Lately I ran into the need for some php memory consumption examination. Sadly the server on which I had to perform this debugging had neither xdebug available nor was php compiled with “–enable-memory-limit” so I could not use memory_get_usage.

Here is a little workaround that was simple but good enough to provide the necessary information. It might not work on windows systems though.Also you should be aware that it will never give you the same results as memory_get_usage(), but it is working well to spot where your memory consumption grows and helps to find leaks.


if ( ! function_exists( 'memory_get_usage' ) ) { 

    function memory_get_usage( $ps_opt="u" ) {
        global $pid;

        $ps=shell_exec("ps ".$ps_opt."p ".$pid);
        $ps=explode("\n", $ps);
            return false;

        $ps=explode(" ", ereg_replace(" +", " ", trim($ps[1])));

        return (int) $ps[4];


$pid = getmypid();

if ( $pid )
    printf( "mem: %d\n", memory_get_usage() );

for ( $i=0; $i<=10000; $i++ ) {
    if ( $i % 1000 == 0 )
        printf( "mem: %d\n", memory_get_usage() );
    $memeater[] = $i*$i;

The important part is in line 3-21.
In line 3-19 a workaround function for memory_get_usage() that uses the “ps” command is defined.
The process id of the currently running PHP process is determined in line 21 and stored within a global variable.
Lines 23++ are just to show an example usage for this code.

Once again – this function is not made to determine any exact memory consumption values or replace memory_get_usage(). It is just a workaround, I use here and there to spot memory leaks in PHP scripts.

One Comment leave one →
  1. April 22, 2009 8:31 PM

    Thats a nice trick… Thanks.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s