PHP Script Usage – Is This a Good Measure?

performancePHP

I've been trying to see a way to get a measure of how much a PHP script costs of memory to the server. Well, I've found some solutions out there that requires some software to make tests and even require to install something on the server. Those solutions are not what I'm looking for, as I just want a simple measure of the consumption.

My try was to do the following:

<?php
     $initialMem = memory_get_usage();
     /* Script comes here */
     $finalMem = memory_get_usage();
     echo ($finalMem - $initialMem)/1024 . " Kbytes";
?>

Where I divided by 1024 to convert from bytes to kilobytes. The idea was that the function memory_get_usage() gets the amount of memory allocated for the execution of the script and so I thought that taking the difference would be a good measure of the usage.

Is this correct? Is the difference between those values a good measure of the usage of memory by the script? If not, how can I get a good measure of this usage without having to install anything on the server?

Best Answer

It doesn't matter how much memory PHP is using. As long as there is enough allocated.

PHP runs in a sandbox inside a webserver. The sandbox is allocated a chunk of memory for use by PHP, and when you hit that limit then PHP throws an out of memory exception. You have to either increase the limit in php.ini or change your code.

PHP scripts do not remain executing after a request is made. The script is terminated and the output buffer is sent to the browser. Your sample source code will only tell you how much memory was used for that HTTP request. The amount of memory used by PHP will change depending upon how many concurrent requests are made to the server, and what that server is configured to handle.

I think the default chunk of memory for PHP is 64MB, but I run mine at 2BG because I have command line cron jobs that are very memory hungry.

How much memory PHP uses is peak = 64MB * concurrent requests.

Related Topic