measuring the elapsed time between code segments in PHP

后端 未结 7 1770
傲寒
傲寒 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:28

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

        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 "\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:

    
    
    

提交回复
热议问题