Home » PHP » PHP Tutorial: Timing Your Code

PHP Tutorial: Timing Your Code

Sometimes you need to know how long a script takes to run, or perhaps just a part of it. Sometimes you can think of two ways to do something and want to know which is the fastest. That's where the microtime() function comes in mighty handy.

$start = microtime(true);
   //code
   //to
   //execute
$end = microtime(true);
$time = $end - $start;
echo "The code completed in $time seconds.";

microtime() gives you the UNIX timestamp (defined as the number of seconds elapsed since midnight UTC on Thursday, January 1, 1970) down to the microsecond (millionth of a second). This is a big number that is basically indecipherable unless you're Rain Man, but you don't need to decipher it. You just need it when you start and when you end, and the end minus the start will give you the amount of time that elapsed between them.

The reason you pass "true" to microtime() is because it makes microtime() return a float, which you can use in a mathematical operation. Otherwise it returns the time as a text string.

Tags: ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>