Get time difference in PHP with microtime()

Description:

Detect how long a script, query or function takes to run in php.

Solution:

PHP offers the microtime() function, which returns the number of microseconds (a millionth of a second) that passed since 1st of January 1970, the PHP epoch.

The way to use it is assigning the microtime() value to a variable before the desired script and then one after, the difference between them being the result we need.

$time_start = microtime();

$run_function = processData();

$time_end = microtime();

$time = $time_end – $time_start;

echo “processData function completed in “.$time.” microseconds”;

Also we can multiply the result by 1 000 000 to get the number of seconds, or manipulate it as we wish, to return the result in any time related way:

echo date(“H:i:s”,$time);

Advertisements

About admin

Just another php developer trying to give something back to the community.
This entry was posted in PhP and tagged , , , . Bookmark the permalink.

3 Responses to Get time difference in PHP with microtime()

  1. littleguy says:

    This only works if you pass TRUE as first parameter, to microtime():

    Example:
    $time_start = microtime(true);
    sleep(5);
    $time_end = microtime(true);
    $time = $time_end – $time_start;
    echo “processData function completed in {$time} microseconds”;

    Without passing true the results are not correct, because they microtime returns a string instead of a double (which you get when you pass true as the first parameter to microtime)

    http://www.php.net//manual/en/function.microtime.php

  2. ashwinbhy says:

    It gives time difference in seconds not milliseconds.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s