我想知道执行一个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

当前回答

创建文件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秒内”

其他回答

您可以用一个函数找到以秒为单位的执行时间。

// ampersand is important thing here
function microSec( & $ms ) {
    if (\floatval( $ms ) == 0) {
        $ms = microtime( true );
    }
    else {
        $originalMs = $ms;
        $ms = 0;
        return microtime( true ) - $originalMs;
    }
}

// you don't have to define $ms variable. just function needs
// it to calculate the difference.
microSec($ms);
sleep(10);
echo microSec($ms) . " seconds"; // 10 seconds

for( $i = 0; $i < 10; $i++) {
    // you can use same variable everytime without assign a value
    microSec($ms);
    sleep(1);
    echo microSec($ms) . " seconds"; // 1 second
}

for( $i = 0; $i < 10; $i++) {
    // also you can use temp or useless variables
    microSec($xyzabc);
    sleep(1);
    echo microSec($xyzabc) . " seconds"; // 1 second
}

您的想法是正确的,不过microtime()函数可以提供更精确的计时。

如果循环内的内容是快速的,则可能的表观消耗时间将为零。如果是这样,则围绕该代码封装另一个循环并重复调用它。请确保将差值除以迭代次数,以得到每一次的时间。我已经分析了需要10,000,000次迭代才能获得一致、可靠的计时结果的代码。

<?php
// Randomize sleeping time
usleep(mt_rand(100, 10000));

// REQUEST_TIME_FLOAT is available in the $_SERVER superglobal array.
// It contains the timestamp of the start of the request with microsecond precision.
$time = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"];

echo "Did nothing in $time seconds\n";
?>

这是这个的链接

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

<?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
?>