title: Measuring execution time of PHP script that serves web content
body: <p>I'm testing the execution time of some PHP scripts whose purpose is to serve web content on my web site.</p>
  
  <p>However I'm getting inconsistent results.</p>
  
  <p>The execution time is measured and logged to a text file.</p>
  
  <p>One of the scripts basically read a jpeg image from disk and serves it to the client.</p>
  
  <p>Here is a simplified version of the script with the relevant code:</p>
  
  <pre><code>&lt;?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 );
  </code></pre>
  
  <p>Images served are every time different. They are around 100KB of size.</p>
  
  <p>I connect to the website from a remote location and load some images.</p>
  
  <p>When I look at the log file execution time in milliseconds looks like this</p>
  
  <pre><code>45
  63
  40
  3
  3
  67
  40
  3
  5
  </code></pre>
  
  <p>I'd expect (<strong>but probably I'm wrong on this</strong>) that when the PHP script sends data to the client execution waits until the data has been sent.</p>
  
  <p>So, in the above code, <code>$t2</code> is retrieved when the image has been completely sent to the client.</p>
  
  <p>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.</p>
  
  <p>Is PHP sending all the data instantly to the web server (it's <strong>nginx</strong> in my case) and then the latter takes its time to send the data to the client?</p>
  
  <hr>
  
  <p><strong>Update</strong></p>
  
  <p>It seem the problem is related to <strong>nginx</strong> doing buffering.</p>
  
  <p>When this does happen <strong>nginx</strong> "eats" the output buffer from PHP as fast as possible and then sends the content to the client.</p>
  
  <p>This allows the PHP instance to be closed sooner.</p>
  
  <p>The PHP script doesn't see the time needed to transfer the content to the client.</p>
  
  <p>Unfortunately there seem to be a no way to disable <strong>nginx</strong> buffering. I've found many "recipes" googling around but no one works.</p>