Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

memory_get_usage

I'm making a little benchmark class to display page load time and memory usage. Load time is already working, but when I display the memory usage, it doesn't change Example:

$conns = array();
ob_start();
benchmark::start();
$conns[] = mysql_connect('localhost', 'root', '');
benchmark::stop();
ob_flush();

uses the same memory as

$conns = array();
ob_start();
benchmark::start();
for($i = 0; $i < 1000; $i++)
{
   $conns[] = mysql_connect('localhost', 'root', '');
}
benchmark::stop();
ob_flush();

I'm using memory_get_usage(true) to get the memory usage in bytes.

like image 839
Qtacz Avatar asked Mar 09 '10 13:03

Qtacz


2 Answers

memory_get_usage(true) will show the amount of memory allocated by the php engine, not actually used by the script. It's very possible that your test script hasn't required the engine to ask for more memory.

For a test, grab a large(ish) file and read it into memory. You should see a change then.

I've successfully used memory_get_usage(true) to track the memory usage of web crawling scripts, and it's worked fine (since the goal was to slow things down before hitting the system memory limit). The one thing to remember is that it doesn't change based on actual usage, it changes based on the memory requested by the engine. So what you end up seeing is sudden jumps instead of slowing growing (or shrinking).

If you set the real_usage flag to false, you may be able to see very small memory changes - however, this won't help you monitor the true amount of memory php is requesting from the system.

(Update: To be clear the difference I describe is between memory used by the variables of your script, compared to the memory the engine requested to run your script. All the same script, different way of measuring.)

like image 110
Tim Lytle Avatar answered Sep 18 '22 14:09

Tim Lytle


I'm no Guru in PHP's internals, but I could imagine an echo does not affect the amount of memory used by PHP, as it just outputs something to the client.

It could be different if you enable output buffering.

The following should make a difference:

$result = null;
benchmark::start()
for($i = 0; $i < 10000; $i++)
{
   $result.='test';
}
like image 33
Pekka Avatar answered Sep 18 '22 14:09

Pekka