Check how much memory your PHP script is using. (PHP script memory usage)

by Yang Yang on September 18, 2010

Depending on the web server software you use, your PHP script will be consuming significantly different amount of memory (RAM). If you are using Apache without proper optimization, the simplest request that does nothing but returns a status code will need 150kB of memory. Multiply this by 2000 visits per day and by 10 sites in a single Linux VPS box, you will have some serious OOM (Out Of Memory) problems.

However if you are using simplistic web server software such as Lighttpd, the situation will get a lot better. But you would still like some improvements to your PHP script itself. So does one first know how much memory a PHP script consumes at run time?

The answer is the memory_get_peak_usage() function. At the end of your PHP script (footer script for a PHP site, you get the idea), put this line:

echo memory_get_peak_usage();

Or you can write the data down in a text file:

file_put_contents('mu.txt', memory_get_peak_usage());

The output is in bytes. Better yet, you can record down the URL request, HTTP request type and memory usage in the mu.txt file so that you can examine it regularly to make adjustments to your server and PHP scripts:

$mu = fopen('mu.txt', 'a');
fwrite($mu, $_SERVER['REQUEST_URI'].', '.$_SERVER['REQUEST_METHOD'].', '.memory_get_peak_usage()."\n");

Comments on this entry are closed.

Previous post:

Next post: