我想知道环一个PHP需要多少毫秒执行。衡量PHP脚本的执行时间准确地
我知道一个通用算法的结构,但不知道如何实现它在PHP:
Begin
init1 = timer(); // where timer() is the amount of milliseconds from midnight
the loop begin
some code
the loop end
total = timer() - init1;
End
我想知道环一个PHP需要多少毫秒执行。衡量PHP脚本的执行时间准确地
我知道一个通用算法的结构,但不知道如何实现它在PHP:
Begin
init1 = timer(); // where timer() is the amount of milliseconds from midnight
the loop begin
some code
the loop end
total = timer() - init1;
End
可以使用microtime
功能这一点。从the documentation:
microtime
- 返回微秒电流Unix时间戳
如果
get_as_float
设置为TRUE
,然后microtime()
返回float,它代表以秒为单位的当前时间自Unix纪元精确到最近的微秒。
实例:
$start = microtime(true);
while (...) {
}
$time_elapsed_secs = microtime(true) - $start;
如果你想用返回值进行计算,你需要'microtime(true)'。 – lonesomeday 2011-06-05 21:29:37
我知道这是waaaaaay太晚了(差不多4年),但作为一个评论...使用这些计算(使用参数'get_as_float'为'true')会给你** **结果**,根据PHP文档。 – 2015-03-31 02:34:09
@AlejandroIván:不,它不。 get_as_float将返回一个FLOAT而不是一个STRING,所以你可以用返回值进行计算......检查http://php.net/manual/en/function.microtime.php:如果get_as_float设置为TRUE,那么microtime()返回一个浮点数,它表示自Unix时期以来的秒数,精确到最近的微秒。 – patrick 2015-07-06 15:13:52
参见microtime()。
$start = microtime(true);
for ($i = 0; $i < 10000; ++$i) {
// do something
}
$total = microtime(true) - $start;
echo $total;
你有正确的想法,但更精确的时序是可用的microtime()功能。
如果里面是什么循环快,有可能是明显的运行时间将为零。如果是这样,围绕代码包装另一个循环,并重复调用它。确保将差异除以迭代次数以获得每次一次的时间。我有需要10,000,000次迭代的简介代码才能获得一致,可靠的计时结果。
在脚本的beggining创建文件loadtime.php
<?php
class loadTime{
private $time_start = 0;
private $time_end = 0;
private $time = 0;
public function __construct(){
$this->time_start= microtime(true);
}
public function __destruct(){
$this->time_end = microtime(true);
$this->time = $this->time_end - $this->time_start;
echo "Loaded in $this->time seconds\n";
}
}
比,后<?php
写include 'loadtime.php'; $loadtime=new loadTime();
当页面是在年底将有写“在x秒加载”
装整洁!但是,如果你没有明确地销毁你的对象,输出将出现在关闭'
可以摆弄)microtime中的大片(报表,如果您需要在此生产,但如果它只是用于测试,只需使用[Xdebug的的分析器(http://www.xdebug.org/docs/profiler)。没有混乱的代码是一个真正的优点。 – Wrikken 2011-06-05 21:39:39