7

I see every one suggests using a variable such as

$start_time = microtime(TRUE);

on top of the script, and then on the final line we do:

$process_time = microtime(TRUE) - $start_time;

My question is, can we reliably use $_SERVER['REQUEST_TIME_FLOAT'] and skip the $start_time altogether? if so, why does every one still suggest using $start_time on top?

Example of what I mean:

<?php
// No need for $start_time...

// All the stuff we do to have the benchmark at the end

// Only this line needed to display execution time
echo "Processed in: ". bcsub(microtime(TRUE), "{$_SERVER['REQUEST_TIME_FLOAT']}", 4);
?>
Bruno Leveque
  • 2,647
  • 2
  • 23
  • 33
J. Doe
  • 812
  • 1
  • 15
  • 33
  • 1
    Possible duplicate of [Measuring the time of PHP scripts - Using $\_REQUEST\['REQUEST\_TIME'\]](https://stackoverflow.com/questions/28703822/measuring-the-time-of-php-scripts-using-requestrequest-time) – Chris White Apr 28 '19 at 00:11
  • @ChrisWhite Thank you, but it doesn't answer my questions and doubts – J. Doe Apr 28 '19 at 00:33

1 Answers1

12

It depends on what you're trying to measure.

$_SERVER['REQUEST_TIME_FLOAT'] is set the moment your webserver hands the processing over to PHP. That means it will always be the timestamp PHP starts processing the request. So if you want to measure how long it took PHP to get to a specific point, you can use that. The downside is that you don't really know what PHP is doing before it gets to your code. There may be files in PHP's auto-prepend configuration that take up processing time before it even reads the first line of your code. But if you actually want to measure that time as well, you have to use this property.

On the other hand, you can ask for microtime(true) whenever you want, which helps when you want to measure the performance of a specific piece of code. For example, maybe you're in an MVC framework and you only want to measure how long it's taking your model to fetch and prepare a database resultset and you don't really care how long it took the framework to figure out which controller/action needed to be called or how long it took your controller to ask your model for information.

rickdenhaan
  • 10,857
  • 28
  • 37
  • 1
    This line explained it perfectly for me: `The downside is that you don't really know what PHP is doing before it gets to your code` , Thanks! – J. Doe Apr 28 '19 at 00:34
  • $_SERVER['REQUEST_TIME_FLOAT'] is filled BEFORE auto-prepend is processed – paranoiq Nov 14 '21 at 10:52
  • @paranoiq Correct. That's what I meant with the last line of the first paragraph. To rephrase that: "if you want to include any time spent in auto-prepend in your measurements, you *have* to use the REQUEST_TIME_FLOAT property". – rickdenhaan Nov 14 '21 at 12:10