Correct way to get server response time in Laravel Correct way to get server response time in Laravel laravel laravel

Correct way to get server response time in Laravel


I used microtime(true) - LARAVEL_START. Seems to give a fairly accurate response time.

As Bogdan mentions in the comment:

The LARAVEL_START constant is defined in bootstrap/autoload.php which is the very first file included from public/index.php, so this makes it the first statement to be executed. If you place the middleware last on the list, its terminate method will be the last one executed before app->terminate() will be called, so you should get a pretty good computation of execution time.


I noticed that in a single request life cycle middleware instance may be initialized more than once. The second time is right before terminate call. That would explain zero time result (on my machine it was not zero but pretty close to it, while the actual request time was more like 200ms). The handle method was obviously called only once and this is where start time must be recorded.

class SendAnalytics implements TerminableMiddleware {    protected $startTime;    public function handle($request, Closure $next) {        $this->startTime = microtime(true);        return $next($request);    }    ...}