-2

I've created a basic application in PHP and would like to print the time it takes to load the page at the end of the page. I first define the start with a microtime and then compare it to the current microtime at the end, the problem is it outputs something like "0.000102" and I'm looking for it in milliseconds, I'm guessing that would be 102ms?

Define the start,

define("START", microtime(true));

Then print the end time.

printf("Page was rendered in %f milliseconds", (microtime(true) - START));

But it still outputs that horrible long string.

1 Answers1

1

Milliseconds is n*1000:

<?php
$start = microtime(true);

usleep(1000000);

$end = microtime(true) - $start;

printf("Page was rendered in %f seconds", $end);
printf("Page was rendered in %f milliseconds", $end*1000);
printf("Page was rendered in %f microseconds", ($end*1000)*1000);

https://3v4l.org/kHmA3

Result:

Page was rendered in 1.000115 seconds
Page was rendered in 1000.115156 milliseconds
Page was rendered in 1000115.156174 microseconds

Edit: If you want values outputted like 0.10 etc you will need to change %f to %s and use round().

<?php
$start = microtime(true);

usleep(1000000);

$end = microtime(true) - $start;

printf("Page was rendered in %s seconds", round($end, 2));
printf("Page was rendered in %s milliseconds", round($end*1000, 2));
printf("Page was rendered in %s microseconds", round(($end*1000)*1000, 2));

https://3v4l.org/OfgJX

Result:

Page was rendered in 1 seconds
Page was rendered in 1000.12 milliseconds
Page was rendered in 1000121.12 microseconds
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
  • Thanks! Is there a way to round the milliseconds to something like "596", I'm currently getting "0.306027" which is pretty complex when I read it. – tivitonel Feb 10 '18 at 19:45
  • Thanks! I seem to be having problems rounding it, the page says it took "0.29706954956055" but my extension says 0.06 (62 milliseconds) ?? – tivitonel Feb 10 '18 at 19:58
  • Im not sure I understand, where is the large float coming from? And what extension? The problem you can get from a script like this, is that unless you do it on the last line of the script or shutdown event, then timings can differ. Like if you output it in a partial view, but the script still needs to render the template then its not going to match. – Lawrence Cherone Feb 10 '18 at 20:01
  • Also your browser will show different values as it accounts for assets like, css images etc. – Lawrence Cherone Feb 10 '18 at 20:02
  • The large float is coming from %s, It's not rounding to a short millisecond properly. I'm trying to display it as "297" but it continues to remain as a very long float. – tivitonel Feb 10 '18 at 20:20
  • Try: `printf("Page was rendered in %s milliseconds", round($end*1000));` - https://3v4l.org/YeRLE – Lawrence Cherone Feb 10 '18 at 20:30
  • Your doing something with `$end` if you pass `0.123` to the above it would produce `123`. – Lawrence Cherone Feb 10 '18 at 20:34