title: PHP memory_get_usage
body: <p>I came across the PHP's <code>memory_get_usage()</code> and <code>memory_get_peak_usage()</code>.</p>
  
  <p>The problem is that I found that these two functions do not provide the real memory used by the current script.
  My test script is:</p>
  
  <pre><code>&lt;?php
  
  echo memory_get_usage();
  
  echo '&lt;br /&gt;';
  
  $a = str_repeat('hello', 100000);
  
  echo '&lt;br /&gt;';
  
  echo memory_get_usage();
  
  echo '&lt;br /&gt;';
  
  echo memory_get_peak_usage();
  
  ?&gt;
  </code></pre>
  
  <p>Which returns:</p>
  
  <p>355120</p>
  
  <p>5355216</p>
  
  <p>5356008</p>
  
  <p>What do you understand from this?</p>
  
  <p>The first value is before executing the <code>str_repeat()</code> so it has to be the value of <code>0</code>.</p>
  
  <p>The second is after the process and it's OK to have a value greater than <code>0</code> but not that big value.</p>
  
  <p>The third is the "peak" value and it's slightly greater than the second as I think it should be the biggest value in a processing microsecond.</p>
  
  <p>So do you think that the real value of the current script's memory consumption should be like this:</p>
  
  <pre><code>memory_usage = the second memory usage - the first memory usage
  
  peak_memory_usage = the third (peak_usage) - the first memory usage
  </code></pre>
  
  <p>which gives:</p>
  
  <p>1) 5355216 - 355120 = 5000096 bytes</p>
  
  <p>2) 5356008 - 355120 = 5000888 bytes</p>
  
  <p>If this is how it works, I assume that the first <code>355120</code> bytes are the whole system allocated memory used by apache and other modules, as the first value never changes when you increase or decrease the number of repeats in the <code>str_repeat()</code>, only the two values after the process increase or decrease but never gets smaller that the first value.</p>