I have yet to find an elegant solution for this. I have a class with a method I want to track the memory usage of without modifying the function:
class Example
{
public function hello($name)
{
$something = str_repeat($name, pow(1024, 2));
}
}
$class = new Example;
$class->hello('a');
So the task is, how much memory does hello() use without interferring with it?
Note: The memory usage of this method should be 1MB. I’ve tried wrapping the call with memory_get_usage(); to no avail:
class Example
{
public function hello($name)
{
$something = str_repeat($name, pow(1024, 2));
}
}
$class = new Example;
$s = memory_get_usage();
$class->hello('a');
echo memory_get_usage() - $s;
This only results in 144 bytes (Not correct at all). I’ve tried various magic with Reflection by using the ReflectionMethod class.
I have a feeling what I need to do is calculate the difference in the method :(. If someone can think of anything cleaner then you’d really make my day.
Edit: I should mention this is in the context of a benchmarking application. So while memory_get_peak_usage works in the sense that it correctly returns the memory usage, it will also skew benchmarks ran after a high memory method. Now if there was a way to reset the memory stats, that could be good also.
You could use
register_tick_functionand just dumpmemeory_get_usageout every tick (line) and analysis it later. The class below could be improved by usingdebug_backtraceto find line number related to memory usage or adding time per line usingmicrotime.Profiler class
Example
Output
Possible Issue
Since this profiler class stores the data in PHP, the overall memory usage will increase artificially. One way to sidestep this issue would be to write the data out to a file as you go (serialized), and when your done you can read it back.