PHP Page Generation Time Code Example Script

PHP Page Generation TimeWhen optimising a website, it’s common for people to measure the PHP page generation time because it is more reliable than the client measuring the total request time which includes network delay which is beyond the scope of the code.

I recently started updating a combined CRM/CMS that I initially developed for an online-only reseller business. Back then, this was how one would usually get microsecond-accurate PHP script generation times. The reason I’m posting this, is not because it’s an integral development for the language but because I see lots of people still recommending the following solution.

The Old Way – Do Not Use!


Even though it isn’t complicated, it’s evidently a lot of code for what is a common process that should be simple and the PHP development community thought so too. This was addressed with the release of PHP 5.4.0 on 2012-03-01 with the introduction of a new $_SERVER variable:

$_SERVER['REQUEST_TIME_FLOAT'] The timestamp of the start of the request, with microsecond precision.

This has removed the necessity of having to be mindful of variable scope, in this case, when people would probably use something dangerously plain such as $start and $finish, then wonder why their PHP page generation time is trying to subtract $start, perhaps re-declared with $mysqli->query() results, from $end; microtime().

PHP Page Generation Time


This one-liner is much more elegant, easier to understand what’s going on at a glance (to other developers) and doesn’t require any additional variable-declarations if you echo the result instead of storing it.

Comments

  • Your code has one mistake –
    $total_time = round((microtime()-$_SERVER['REQUEST_TIME_FLOAT']), 4);

    you must use microtime(true) to have float.

    The right code is

    $total_time = round((microtime(true)-$_SERVER['REQUEST_TIME_FLOAT']), 4);

    Thanks!

    • Thanks for spotting that, gmelikov! I deleted the old gist and put working code up haha.

  • Sergey

    Use microtime(true):

    http://www.php.net/manual/en/function.microtime.php :
    If used and set to TRUE, microtime() will return a float instead of a string, as described in the return values section below.

    • You’re right, Sergey! It was not functioning in the gist revisions I had embedded. I’m glad you got it working though and thanks for posting here so I knew to fix it!

Leave a Comment