测量 PHP 中代码段之间经过的时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11235369/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:02:01  来源:igfitidea点击:

measuring the elapsed time between code segments in PHP

phptime

提问by Average Joe

From time time to time, I'd like to be able to measure the elapsed time between two segments of code. This is solely to be able to detect the bottlenecks within the code and improve what can be improved.

有时,我希望能够测量两段代码之间经过的时间。这仅仅是为了能够检测代码中的瓶颈并改进可以改进的内容。

I'd like to design a function like that where the function should work with a global variable which echoes out the elapsed time between the current call and the last time it was called.

我想设计一个这样的函数,其中该函数应该与一个全局变量一起工作,该变量可以反映当前调用和上次调用之间经过的时间。

This way, you can use it many times one after the other.

这样,您可以一个接一个地多次使用它。

And the function should be able to be calculate the differences in fractions of seconds such as 0.1 sec or 0.3 sec etc.

并且该函数应该能够计算几分之一秒的差异,例如 0.1 秒或 0.3 秒等。

An example would probably explain it much better.

一个例子可能会更好地解释它。

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

My question is what PHP utilities ( built-in functions ) do I need to use to achieve this kind of output?

我的问题是我需要使用哪些 PHP 实用程序(内置函数)来实现这种输出?

回答by drew010

A debugger like XDebug/Zend Debugger can give you this type of insight (plus much more), but here is a hint at how you can write a function like that:

像 XDebug/Zend Debugger 这样的调试器可以给你这种类型的洞察力(还有更多),但这里有一个关于如何编写这样的函数的提示:

function time_elapsed()
{
    static $last = null;

    $now = microtime(true);

    if ($last != null) {
        echo '<!-- ' . ($now - $last) . ' -->';
    }

    $last = $now;
}

Mainly the function microtime()is all you need in order to do the time calculations. To avoid a global variable, I use a static variable within the elapsed function. Alternatively, you could create a simple class that can encapsulate the required variables and make calls to a class method to track and output the time values.

主要是函数microtime()是您进行时间计算所需的全部内容。为了避免使用全局变量,我在 elapsed 函数中使用了一个静态变量。或者,您可以创建一个简单的类,该类可以封装所需的变量并调用类方法来跟踪和输出时间值。

回答by HamZa

From the first example in the php docs:

php docs 中的第一个示例:

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

回答by David

Something along these lines should work:

沿着这些路线的东西应该工作:

$start = microtime(true); 

// Do something
sleep(2);

$end = (microtime(true) - $start);
echo "elapsed time: $end";

回答by Andrew SparklingDiamond James

Other factors affect the timing of your scripts. Example:

其他因素会影响脚本的时间。例子:

  1. Complex code and recursive functions.
  2. The type of web server being used, example: shared VS dedicated hosting.
  1. 复杂的代码和递归函数。
  2. 正在使用的 Web 服务器的类型,例如:共享 VS 专用托管。

回答by Rudy

Same drew010 function (thanks!), only added custom comment and time displays in microseconds (us):

相同的 draw010 函数(谢谢!),仅添加了自定义注释和时间显示(以微秒为单位):

    function time_elapsed($comment) 
        {

        static $time_elapsed_last = null;
        static $time_elapsed_start = null;

        // $unit="s"; $scale=1000000; // output in seconds
        // $unit="ms"; $scale=1000; // output in milliseconds
        $unit="μs"; $scale=1; // output in microseconds

        $now = microtime(true);

        if ($time_elapsed_last != null) {
            echo "\n";
            echo '<!-- ';
            echo "$comment: Time elapsed: ";
            echo round(($now - $time_elapsed_last)*1000000)/$scale;
            echo " $unit, total time: ";
            echo round(($now - $time_elapsed_start)*1000000)/$scale;
            echo " $unit -->";
            echo "\n";
        } else {
            $time_elapsed_start=$now;
        }

        $time_elapsed_last = $now;
    }               

Example:

例子:

// Start timer
time_elapsed('');

// Do something
usleep(100);
time_elapsed('Now awake, sleep again');

// Do something
usleep(100);
time_elapsed('Game over');

Ouput:

输出:

<!-- Now awake, sleep again: Time elapsed: 100 us, total time: 100 us -->
<!-- Game over: Time elapsed: 100 us, total time: 200 us -->

回答by Tadej

<?php
$time_start = microtime(true);

// Sleep for a while (or your code which you want to measure)
usleep(100);

$time_end = microtime(true);
$time = $time_end - $time_start;

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

Source: http://php.net/manual/en/function.microtime.php#example-2568

来源:http: //php.net/manual/en/function.microtime.php#example-2568

回答by syck

My profiling needs in development are covered by this small yet powerful class:

这个小而强大的类涵盖了我在开发中的分析需求:

<?php

class perflog {
    protected $perflog = [];

    public function start($tag) {
        if (!isset($this->perflog[$tag])) $this->perflog[$tag] = 0;
        $this->perflog[$tag] -= microtime(TRUE);
    }

    public function stop($tag) {
        $this->perflog[$tag] += microtime(TRUE);
    }

    public function results() {
        return $this->perflog;
    }
}

See it in action here.

在这里查看它的实际效果。

It is intended to be invoked via subsequent start(<tag>)and stop(<tag>)calls. It produces an array with the totalized times your code spent in the sections enclosed by the calls of start() and stop() with matching tags.

它旨在通过后续start(<tag>)stop(<tag>)调用来调用。它生成一个数组,其中包含您的代码在带有匹配标签的 start() 和 stop() 调用所包含的部分中花费的总时间。

start-stop sequences may be nested and may be entered multiple times, thus summarizing the time spent in the enclosed section.

起止序列可以嵌套并且可以多次输入,从而总结在封闭部分中花费的时间。

Its compactness ensures minimum performance impact. Dynamic tag creation can be used to let the program modify what it monitors. Typically this is extended with outputting or storing functions.

它的紧凑性确保了最小的性能影响。动态标记创建可用于让程序修改它所监视的内容。通常,这是通过输出或存储功能进行扩展的。