How to use microtime() in PHP

I was recently creating a simple quiz game and needed to record the time between a question being presented and an answer being given. Using the microtime() function in PHP was one simple way to track the time taken down to the microsecond.

The function is easy to use. The format is:

<?php

echo microtime(true);

The output is as follows:

1515582825.0566

Now, combining a couple of variables and a little calculation will allow you to track the time taken.

<?php

//question is presented

$startTime = microtime(true);

//user answers the question. To simulate the time taken we can sleep for a few microseconds

usleep(mt_rand(10000, 1000000));

$endTime = microtime(true);

//we now calculate the time taken

$timeTaken = $endTime - $startTime;

echo "The time taken was: ", $timeTaken;

Hopefully the code is self explanatory but feel free to ask questions in the comments.

Obviously, we are reliant on many external variables such as internet speed, local browser render speed, server etc but I think this provides a very simple method for calculating the time taken.

If you would like to learn more about PHP then enrol in the PHP for Beginners course.

Want to Learn More?

Become a member and get access to the member only area of this site here.

Comments

Your email address will not be published.

PHP for Beginners

Enrol in the full course here

PHP, MySQL and PDO

Coming soon, a full course on using PHP, MySQL and PDO. Be notified as soon as the course goes live.