measuring the elapsed time between code segments in PHP

后端 未结 7 1750
傲寒
傲寒 2020-12-15 19:32

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 an

相关标签:
7条回答
  • 2020-12-15 20:33

    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;
    }
    

    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.

    0 讨论(0)
提交回复
热议问题