Greg Aker

Showing PHP Memory Usage through your Template

Filed in: Performance, PHP, ExpressionEngine

June 18, 2011

Ever been deep in troubleshooting performance issues in your ExpressionEngine site and wondered what kind of memory is a certain plugin/weblog tag, etc is taking up? Unless you're holding out from blogging about it, there's absolutely no way I'm aware of that you're getting that info from shell on the server. So, here's a quick and dirty hack to EE's template parser that will show you this info.

Pop open system/expressionengine/libraries/Template.php and look for:

<?php

function log_item($str)

Now, a quick addition in there and you're good to go. We'll add calls to PHP's memory_get_usage function if it's available to our system. Rewrite the function so it looks like:

<?php

function log_item($str)
{
    if ($this->debugging !== TRUE)
    {
        return;
    }

    if ($this->depth > 0)
    {
        $str = str_repeat('&nbsp;', $this->depth * 5).$str;
    }

    $time = microtime(TRUE)-$this->start_microtime;

    if (function_exists('memory_get_usage'))
    {
        $str = $str . ' - Mem: ' .round(memory_get_usage()/1024/1024, 2).'MB';
    }

    $this->log[] = '('.number_format($time, 6).') '.$str;
}

and you should get some more information to help you narrow down where a high memory usage performance issue is biting you. Remember, channel/weblog/comments tags are big dogs, so you can expect a jump there. Same goes for when files for addons are 'included' for processing.

When you look at your template debugging, you'll see something like:

You can't get this in top

Props to Nevin Lyne for the late-night idea.