3

Is it possible to get the peak memory usage of a particular block of code in PHP? The memory_get_peak_usage() function seems to get the peak over the entire process execution up to the point of the function call, but this is not what I'm trying to obtain, since other code blocks could have skewed the value. I'm trying to isolate code blocks themselves, rather than the process as a whole.

Example:

// Block 1
for ($i = 0; $i < $iterations; ++$i) {
    // some code
}

// Block 2
for ($i = 0; $i < $iterations; ++$i) {
    // some different code
}

// Determine which of the two blocks used the most memory during their execution here

Unfortunately, xdebug is not an option for me at this time.

FtDRbwLXw6
  • 27,774
  • 13
  • 70
  • 107

2 Answers2

-1

I don't know a specific function that does this, but if you are just trying to isolate a block of code does something as simple as:

$before = memory_get_peak_usage();
for ($i = 0; $i < $iterations; ++$i) {
    // some code
}
$after = memory_get_peak_usage();
$used_memory = $after - $before;
Craig Traynor
  • 449
  • 2
  • 6
  • 15
  • I explained in my question why this does not work. – FtDRbwLXw6 Feb 20 '13 at 18:14
  • Just using it once would give you the peak over the whole code up to that point. However having a variable before and after and subtracting will give you the peak memory usage of that function. – Craig Traynor Feb 20 '13 at 18:40
  • 1
    This will not work the way you think it will for the reasons I outlined in my question. Because `memory_get_peak_usage()` maintains a running *maximum*, if the code block you've wrapped uses *less* than that maximum, the subsequent call will still show that maximum, and your `$used_memory` will be 0. – FtDRbwLXw6 Feb 20 '13 at 19:08
-1

EDIT: XHProf does it, check my answer here.


Don't use memory_get_peak_usage():

$alpha = memory_get_usage();

for ($i = 0; $i < $iterations; ++$i) {
    // some code
}

$used_memory = memory_get_usage() - $alpha;

Bare in mind that this will only return the final amount of memory your // some code needed. Intermediate memory consumption (such as setting / destroying stuff or calling functions) won't count.

You can hack your way using register_tick_function() but it still won't work for function calls.

Community
  • 1
  • 1
Alix Axel
  • 151,645
  • 95
  • 393
  • 500
  • Thank you for your answer, but I specified in the title and question that I'm after the *peak* memory usage of a code block. – FtDRbwLXw6 May 13 '13 at 13:13
  • @drrcknlsn: I'm after the same thing (http://stackoverflow.com/q/16511611/89771) but I don't think it's any good. Anyway, like I said in my answer, if you don't care about external function calls in your blocks, you can still get the peak memory usage using the `register_tick_function()`. – Alix Axel May 13 '13 at 13:23
  • @drrcknlsn: Updated it with a link. – Alix Axel May 22 '13 at 03:34