I was digging in the PHP manual and I found the memtrack
extension, not perfect but it's something.
EDIT: I had heard about it, but never actually tried it before. Turns out XHProf is all I needed:
$flags = array
(
XHPROF_FLAGS_CPU,
XHPROF_FLAGS_MEMORY,
XHPROF_FLAGS_NO_BUILTINS,
);
$options = array
(
'ignored_functions' => array
(
'call_user_func',
'call_user_func_array',
'xhprof_disable',
),
);
function hog($i = 1) // uses $i * 0.5 MiB, returns $i * 0.25 MiB
{
$s = str_repeat('a', $i * 1024 * 512); return substr($s, $i * 1024 * 256);
}
Test #1:
xhprof_enable(array_sum($flags), $options);
hog(4);
$profile = xhprof_disable();
print_r($profile);
Output:
[main()==>hog] => Array
(
[ct] => 1
[wt] => 54784
[mu] => 384
[pmu] => 3142356
)
[main()] => Array
(
[ct] => 1
[wt] => 55075
[mu] => 832
[pmu] => 3142356
)
mu
is memory usage, pmu
is peak memory usage, 3142356 / 1024 / 1024 / 0.5 = 4 = $i
.
Test #2 (without XHPROF_FLAGS_NO_BUILTINS
):
[hog==>str_repeat] => Array
(
[ct] => 1
[wt] => 21890
[cpu] => 4000
[mu] => 2097612
[pmu] => 2094200
)
[hog==>substr] => Array
(
[ct] => 1
[wt] => 17202
[cpu] => 4000
[mu] => 1048992
[pmu] => 1048932
)
[main()==>hog] => Array
(
[ct] => 1
[wt] => 45978
[cpu] => 8000
[mu] => 1588
[pmu] => 3143448
)
[main()] => Array
(
[ct] => 1
[wt] => 46284
[cpu] => 8000
[mu] => 2132
[pmu] => 3143448
)
Whoohoo! Thanks Facebook!
From the XHProf docs:
It is worth clarifying that that XHProf doesn't strictly track each allocation/free operation. Rather it uses a more simplistic scheme. It tracks the increase/decrease in the amount of memory allocated to PHP between each function's entry and exit. It also tracks increase/decrease in the amount of peak memory allocated to PHP for each function.