PHP Microtime Tutorial | Chris Page

PHP Microtime Tutorial

Aug 28

Every once in awhile one has to write a script that is concerned with execution time. Consider the following snippet that utilizes epoch seconds to calculate execution time:

$start_time = microtime(true);
usleep(200000);  // sleep 2 seconds
$end_time = microtime(true);

echo 'Execution time:  ' . ($end_time - $start_time) . "\n";

Pretty straight forward and has many useful applications. By using built in php functions, `microtime` and `usleep`, it’s easy to benchmark operations, and even set time limits on operations. Consider the next snippet which will halt execution after 30 seconds:

$max_execution_time = 30;
$start_time = microtime(true);

while (1) {
    if ((microtime(true) - $start_time) > $max_execution_time)) {

    //Do something

One more clever application, is to pace your scripts. Such may be useful when concerned with load:

while (1) {
     usleep(10000);  // sleep 1/10th of a second
    //Send a request... query a DB... do something

You can do quite a bit with these two functions. It never hurts to read up on microtime, and usleep. Enjoy!

Leave a Reply