PHP's Memory Usage

This is a handy little Snippet that goes well with PHP Microtime. Not only are we concerned with our scripts execution time but we also want to make sure we are not using an exorbitant amount of memory in the process.

At the top of your script lets place the code that will start PHP’s Micro time.


$time_start = microtime(true);

At the bottom of your page, just before the “” tag we will put the Code that will calculate the execution time as well as how much memory was used to execute the script.


// RENDER TIME
$time_end = microtime(true);
$time = $time_end - $time_start;

echo "Loaded in n";
echo round($time, 3)." Seconds <br />";
echo 'Peak: ' . number_format(memory_get_peak_usage(), 0, '.', ',') . " bytesn <br />";
echo 'End: ' . number_format(memory_get_usage(), 0, '.', ',') . " bytesn";

number_format() simply formats the number out put to look something like this “111,964″ instead of “111964″.

memory_get_peak_usage() is going to return a value based on the peak memory used during the execution. This is more so were we want to see improvements made.

memory_get_usage() will return the amount of memory used once the script is done processing, basically the amount currently used once the crunching is finished.

It’s a good idea to think about memory usage when you are making web applications as this can impact your hosting.

Say you have a VPS server with 256mb of ram but the foot print of each user is 25mb you can can only have about 10 people accessing your site before you running server errors exceeding memory limits. Any work involving processing of images a lot of data manipulation can eat up memory in a hurry.

Signup for my mailing list

Receive other rambings like this on design, code, and some times food.