我想知道执行一个PHP for循环需要多少毫秒。

我知道一个泛型算法的结构,但不知道如何在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

$times = [];
$nbrOfLoops = 4;
for ($i = 0; $i < $nbrOfLoops; ++$i) {
    $start = microtime(true);
    sleep(1);
    $times[] = microtime(true) - $start;
}

echo 'Average: ' . (array_sum($times) / count($times)) . 'seconds';

其他回答

你可以通过以下方式使用微时间(true):

把这个放在你的php文件的开头:

//place this before any script you want to calculate time
$time_start = microtime(true);

//你的脚本代码在这里

// do something

把这个放在你的php文件的末尾:

// Display Script End time
$time_end = microtime(true);

//dividing with 60 will give the execution time in minutes other wise seconds
$execution_time = ($time_end - $time_start)/60;

//execution time of the script
echo '<b>Total Execution Time:</b> '.$execution_time.' Mins';

它将在几分钟内输出结果。

这里有一个函数,可以计时PHP代码的任何部分的执行,很像Python的timeit模块:https://gist.github.com/flaviovs/35aab0e85852e548a60a

如何使用:

include('timeit.php');
const SOME_CODE = '
        strlen("foo bar");
';
$t = timeit(SOME_CODE);
print "$t[0] loops; $t[2] per loop\n";

结果:

$ php x.php 
100000 loops; 18.08us per loop

免责声明:我是本文主旨的作者

EDIT: timeit现在是https://github.com/flaviovs/timeit上一个独立的、独立的项目

创建文件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: loadtime.php美元loadtime = new loadtime ();

当页面加载结束时,会写“加载在x秒内”

这里有一个非常简单而简短的方法

<?php
$time_start = microtime(true);
//the loop begin
//some code
//the loop end
$time_end = microtime(true);
$total_time = $time_end - $time_start;
echo $total_time; // or whatever u want to do with the time
?>