PHP Tutorial: Timing Your Code
|April 27, 2012||Posted by Greg Bulmash under PHP|
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.