我目前正在制作一个PHP计时器,用于检查某种完成某件事的方法与完成相同的一项工作(基本上是基准测试)相比要花费多少时间。
现在,我还想使该工具能够分辨出该特定方法占用了多少内存。
因此,有关更多信息,我正在使用microtime来检查开始时间,对该代码执行200万次循环,然后使用一些数学方法进行另一个microtime来检查所花费的时间,所以我想在外面微型时间范围,还检查内存使用情况。
这是我当前的代码:
// Set the amount of loops to do, default is 2000
$loops = 2000;
$start_time = microtime(true); // Start the timer
for($i = 0; $i < $loops; $i++) {
// Code to test
}
$total_time = microtime(true) - $start_time; // Stop the timer, and figure out the total
ob_end_flush(); // Enable output again
echo $total_time; // Echo the timer's result
?>
Run Code Online (Sandbox Code Playgroud)
如果您至少使用5.2,则memory_get_peak_usage()应该可以正常工作。
http://php.net/manual/zh/function.memory-get-peak-usage.php
您可以在循环之前调用它一次,以了解到那时的基线,然后在循环之后再次查看它的峰值。
修改您的代码...
// Set the amount of loops to do, default is 2000
$loops = 2000;
$base_mem = memory_get_peak_usage();
$start_time = microtime(true); // Start the timer
for($i = 0; $i < $loops; $i++) {
// Code to test
}
$end_time = microtime(true); // Stop the timer
$extra_mem = memory_get_peak_usage();
// figure out the totals
$total_time = $end_time - $start_time;
$total_mem = $extra_mem - $base_mem;
ob_end_flush(); // Enable output again
echo "Total Time: $total_time\n";
echo "Total Mem Above Basline: $total_mem bytes\n";
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2624 次 |
| 最近记录: |