19

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?

Average Joe
  • 4,521
  • 9
  • 53
  • 81

7 Answers7

23

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.

drew010
  • 68,777
  • 11
  • 134
  • 162
  • i think static variable is saved only within a function and global in the whole script, for example if there is static $a = 4 in a function, if you echo $a outside the function you'll get an error, but if you set global $a, and you echo it outside the function you'll get 4, also, a static variable value is saved for the next time ex: static $a = 1; $a++;echo $a; and when you use the function again it will echo 2, sorry for the long and unclear comment :) – HamZa Jun 27 '12 at 22:36
  • 2
    When a variable is declared [static](http://www.php.net/manual/en/language.variables.scope.php#language.variables.scope.static) it is local to the function, but doesn't lose its value between function calls. When used within a class, its value is shared among all instances of the class. – drew010 Jun 27 '12 at 22:37
15

From the first example in the php docs:

<?php
/**
 * Simple function to replicate PHP 5 behaviour
 */
function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

$time_start = microtime_float();

// Sleep for a while
usleep(100);

$time_end = microtime_float();
$time = $time_end - $time_start;

echo "Did nothing in $time seconds\n";
HamZa
  • 14,671
  • 11
  • 54
  • 75
  • 7
    instead of your microtime_float function just use microtime(true) and you will get a float.. http://php.net/microtime – S.. May 28 '17 at 13:19
10

Something along these lines should work:

$start = microtime(true); 

// Do something
sleep(2);

$end = (microtime(true) - $start);
echo "elapsed time: $end";
HamZa
  • 14,671
  • 11
  • 54
  • 75
David
  • 2,365
  • 8
  • 34
  • 59
3

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 "$comment: Time elapsed: ";
            echo round(($now - $time_elapsed_last)*1000000)/$scale;
            echo " $unit, total time: ";
            echo round(($now - $time_elapsed_start)*1000000)/$scale;
            echo " $unit -->";
            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:

<!-- Now awake, sleep again: Time elapsed: 100 us, total time: 100 us -->
<!-- Game over: Time elapsed: 100 us, total time: 200 us -->
Rudy
  • 181
  • 2
  • 10
  • liked it very much. may be a good idea to add an option to display in terms of seconds too; -> ``. Also, what the `us` stand for here? – Average Joe Jun 20 '14 at 12:25
  • @Average Joe Thank you. μs (Greek mu - s) stays for microseconds = 1/1,000,000 second. This is the native precision of `microtime`. Added the option to display elapsed time in seconds and in milliseconds – Rudy Jul 10 '14 at 02:54
2

Other factors affect the timing of your scripts. Example:

  1. Complex code and recursive functions.
  2. The type of web server being used, example: shared VS dedicated hosting.
HamZa
  • 14,671
  • 11
  • 54
  • 75
2
<?php
$time_start = microtime(true);

// Sleep for a while (or your code which you want to measure)
usleep(100);

$time_end = microtime(true);
$time = $time_end - $time_start;

echo "Did nothing in $time seconds\n";

Source: http://php.net/manual/en/function.microtime.php#example-2568

tedi
  • 6,350
  • 5
  • 52
  • 67
1

My profiling needs in development are covered by this small yet powerful class:

<?php

class perflog {
    protected $perflog = [];

    public function start($tag) {
        if (!isset($this->perflog[$tag])) $this->perflog[$tag] = 0;
        $this->perflog[$tag] -= microtime(TRUE);
    }

    public function stop($tag) {
        $this->perflog[$tag] += microtime(TRUE);
    }

    public function results() {
        return $this->perflog;
    }
}

See it in action here.

It is intended to be invoked via subsequent start(<tag>) and stop(<tag>) calls. It produces an array with the totalized times your code spent in the sections enclosed by the calls of start() and stop() with matching tags.

start-stop sequences may be nested and may be entered multiple times, thus summarizing the time spent in the enclosed section.

Its compactness ensures minimum performance impact. Dynamic tag creation can be used to let the program modify what it monitors. Typically this is extended with outputting or storing functions.

syck
  • 2,984
  • 1
  • 13
  • 23