The*_*per 10 php memory methods function
我还没有找到一个优雅的解决方案.我有一个类,我希望在不修改函数的情况下跟踪内存使用情况:
class Example
{
public function hello($name)
{
$something = str_repeat($name, pow(1024, 2));
}
}
$class = new Example;
$class->hello('a');
Run Code Online (Sandbox Code Playgroud)
所以任务是,在hello()没有干扰的情况下使用多少内存?
注意:此方法的内存使用量应为1MB.我试过打包电话memory_get_usage();无济于事:
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;
Run Code Online (Sandbox Code Playgroud)
这只会产生144字节数(根本不正确).我通过使用ReflectionMethod该类尝试了各种魔法.
我有一种感觉,我需要做的是计算方法的差异:(.如果有人能想到更干净的东西那么你真的会让我的一天.
编辑:我应该提到这是在基准测试应用程序的上下文中.因此,虽然memory_get_peak_usage在正确返回内存使用的意义上工作,但它也会在高内存方法之后运行基准测试.现在,如果有办法重置内存统计数据,那也可能是好的.
你可以使用register_tick_function并只是转memeory_get_usage出每个tick(行)并稍后进行分析.通过使用debug_backtrace查找与内存使用相关的行号或使用每行添加时间,可以改进下面的类microtime.
Profiler类
class Profiler
{
private $_data_array = array();
function __construct()
{
register_tick_function( array( $this, "tick" ) );
declare(ticks = 1);
}
function __destruct()
{
unregister_tick_function( array( $this, "tick" ) );
}
function tick()
{
$this->_data_array[] = array(
"memory" => memory_get_usage(),
"time" => microtime( TRUE ),
//if you need a backtrace you can uncomment this next line
//"backtrace" => debug_backtrace( FALSE ),
);
}
function getDataArray()
{
return $this->_data_array;
}
}
Run Code Online (Sandbox Code Playgroud)
例
class Example
{
public function hello($name)
{
$something = str_repeat($name, pow(1024, 2));
}
}
$profiler = new Profiler(); //starts logging when created
$class = new Example;
$class->hello('a');
$data_array = $profiler->getDataArray();
unset( $profiler ); //stops logging when __destruct is called
print_r( $data_array );
Run Code Online (Sandbox Code Playgroud)
产量
Array (
[0] => Array (
[memory] => 638088
[time] => 1290788749.72
)
[1] => Array (
[memory] => 638896
[time] => 1290788749.72
)
[2] => Array (
[memory] => 639536
[time] => 1290788749.72
)
[3] => Array (
[memory] => 640480
[time] => 1290788749.72
)
[4] => Array (
[memory] => 1689800 // <~ money!
[time] => 1290788749.72
)
[5] => Array (
[memory] => 641664
[time] => 1290788749.72
)
)
Run Code Online (Sandbox Code Playgroud)
可能的问题
由于此探查器类将数据存储在PHP中,因此总体内存使用量将人为增加.避免此问题的一种方法是将数据写入文件(序列化),完成后可以将其读回.