测量PHP中代码段之间的经过时间 [英] measuring the elapsed time between code segments in PHP

查看:80
本文介绍了测量PHP中代码段之间的经过时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不时地希望能够测量两段代码之间的经过时间.这仅仅是为了能够检测代码中的瓶颈并改进可以改进的地方.

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.

并且该函数应该能够计算以秒为单位的差异,例如0.1秒或0.3秒等.

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.

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

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

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

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

推荐答案

像XDebug/Zend Debugger这样的调试器可以为您提供这种类型的见解(还有更多内容),但是这里提示您如何编写类似

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:

function time_elapsed()
{
    static $last = null;

    $now = microtime(true);

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

    $last = $now;
}

主要需要功能 microtime()即可进行时间计算.为了避免全局变量,我在经过的函数中使用了静态变量.另外,您可以创建一个简单的类,该类可以封装所需的变量,并调用类方法以跟踪和输出时间值.

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.

这篇关于测量PHP中代码段之间的经过时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆