Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

measuring the elapsed time between code segments in PHP

Tags:

php

time

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.

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?

like image 348
Average Joe Avatar asked Jun 27 '12 21:06

Average Joe


People also ask

How does PHP calculate elapsed time?

Find elapsed time in php using microtime. <? php $s = microtime(true); sleep(1); // 1 seconds $e = microtime(true); $timediff = $e - $s; echo 'Elapsed time (seconds): ' . sprintf('%0.2f', $timediff) .

How do you calculate elapsed time in Javascript?

getTime() - startTime. getTime(); Note: the getTime() built-in date function returns the elapsed time between Jan 1st, 1970 00:00:00 UTC and the given date.

How do I get elapsed time in Swift?

func time <A> (f: @autoclosure () -> A) -> (result:A, duration: String) { let startTime = CFAbsoluteTimeGetCurrent() let result = f() let endTime = CFAbsoluteTimeGetCurrent() return (result, "Elapsed time is \(endTime - startTime) seconds.") }


1 Answers

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.

like image 103
drew010 Avatar answered Oct 21 '22 22:10

drew010