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?
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) .
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.
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.") }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With