Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Measuring execution time of PHP script that serves web content

I'm testing the execution time of some PHP scripts whose purpose is to serve web content on my web site.

However I'm getting inconsistent results.

The execution time is measured and logged to a text file.

One of the scripts basically read a jpeg image from disk and serves it to the client.

Here is a simplified version of the script with the relevant code:

<?php

// save initial time 
$t1 = microtime(true);

// set header for a jpeg image
header('Content-Type: image/jpeg');

// read a file from the hard drive and send content
// (the real code serves every time a different image based on the request)
readfile( 'the_image.jpg' );

// flush output buffer
flush();
ob_flush();

// save final time
$t2 = microtime(true);

// elapsed time in milliseconds
$te = round( ( $t2 - $t1 ) * 1000 );

// write a line to the log file
$handle = fopen( 'log.txt', 'a' );
fwrite( $handle, $te . "\n" );
fclose( $handle );

Images served are every time different. They are around 100KB of size.

I connect to the website from a remote location and load some images.

When I look at the log file execution time in milliseconds looks like this

45
63
40
3
3
67
40
3
5

I'd expect (but probably I'm wrong on this) that when the PHP script sends data to the client execution waits until the data has been sent.

So, in the above code, $t2 is retrieved when the image has been completely sent to the client.

So why, sometimes, the image takes just 3 ms to be sent? 3 ms is impossible to achieve given the internet connection I'm using when connected to the server.

Is PHP sending all the data instantly to the web server (it's nginx in my case) and then the latter takes its time to send the data to the client?


Update

It seem the problem is related to nginx doing buffering.

When this does happen nginx "eats" the output buffer from PHP as fast as possible and then sends the content to the client.

This allows the PHP instance to be closed sooner.

The PHP script doesn't see the time needed to transfer the content to the client.

Unfortunately there seem to be a no way to disable nginx buffering. I've found many "recipes" googling around but no one works.

like image 517
Paolo Avatar asked Nov 10 '22 02:11

Paolo


1 Answers

  1. my other answer
  2. there are more Caching systems. Your HDD, Your OS and PHP have all a caching system which are doing his job to optimize loading files. You can only see how long PHP needs to load your file.

If you want to see how long your client need to load it, then you have to use JS.

And dont forget, that your browser have a caching system too. You can disable it with Headers or different URL's

like image 158
A. Blub Avatar answered Nov 12 '22 18:11

A. Blub