有时,我希望能够测量两段代码之间的经过时间.这仅仅是为了能够检测代码中的瓶颈并改进可以改进的内容.
我想设计一个类似于函数的函数,其中函数应该使用全局变量,该变量回显当前调用和上次调用之间经过的时间.
这样,您可以一个接一个地使用它.
并且该函数应该能够计算分数秒的差异,例如0.1秒或0.3秒等.
一个例子可能会更好地解释它.
echo time_elapsed();
// This echo outputs nothing cause this is the starting case.
// There is nothing to compare against.
//
// 1st code section here
//
echo time_elapsed();
// This echo outputs 0.5 seconds.
// ...which means there has been 0.5 seconds passed
// ...since the last time time_elapsed() was fired
//
// 2nd code section here
//
echo time_elapsed()
// This echo outputs 0.2 seconds
//
// 3rd code section here
//
echo time_elapsed()
// This echo outputs 0.1 seconds etc
Run Code Online (Sandbox Code Playgroud)
我的问题是我需要使用哪些PHP实用程序(内置函数)来实现这种输出?
dre*_*010 23
像XDebug/Zend Debugger这样的调试器可以为您提供这种类型的洞察力(以及更多),但这里提示您如何编写这样的函数:
function time_elapsed()
{
static $last = null;
$now = microtime(true);
if ($last != null) {
echo '<!-- ' . ($now - $last) . ' -->';
}
$last = $now;
}
Run Code Online (Sandbox Code Playgroud)
主要是函数microtime()是您进行时间计算所需的全部.为了避免全局变量,我在经过的函数中使用了一个静态变量.或者,您可以创建一个简单的类,它可以封装所需的变量,并调用类方法来跟踪和输出时间值.
Ham*_*mZa 13
从php doc s中的第一个例子:
<?php
/**
* Simple function to replicate PHP 5 behaviour
*/
function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
$time_start = microtime_float();
// Sleep for a while
usleep(100);
$time_end = microtime_float();
$time = $time_end - $time_start;
echo "Did nothing in $time seconds\n";
Run Code Online (Sandbox Code Playgroud)
遵循以下原则应该可以:
$start = microtime(true);
// Do something
sleep(2);
$end = (microtime(true) - $start);
echo "elapsed time: $end";
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19422 次 |
| 最近记录: |