Page 520 - Beginning PHP 5.3
P. 520

Part III: Using PHP in Practice
                   Note that using  echo()  only displays the number of seconds to two decimal places. To see the floating -
                  point number more precisely, you can use   printf() :
                    // Displays, for example, “1230613358.459682”
                    printf( “%0.6f”, microtime( true ) );

                   One common scenario where microseconds are useful is when benchmarking your code to find speed
                 bottlenecks. By reading the   microtime()  value before and after performing an operation, and then
                 subtracting one value from the other, you can find out how long the operation took to execute. Here ’ s an
                 example:

                      < !DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
                     “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd” >
                      < html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en” >
                       < head >
                         < title > Timing script execution < /title >
                         < link rel=”stylesheet” type=”text/css” href=”common.css” / >
                       < /head >
                       < body >

                         < h1 > Timing script execution < /h1 >
                      < ?php

                    // Start timing
                    $startTime = microtime( true );

                    // Perform the operation
                    for ( $i=0; $i < 10; $i++ ) {
                      echo “ < p > Hello, world! < /p > ”;
                    }

                    // Stop timing
                    $endTime = microtime( true );
                    $elapsedTime = $endTime - $startTime;
                    printf( “ < p > The operation took %0.6f seconds to execute. < /p > ”, $elapsedTime );

                    ? >
                       < /body >
                      < /html >
                   You can see a sample output from this script in Figure 16 - 1.


















              482





                                                                                                      9/21/09   9:15:31 AM
          c16.indd   482                                                                              9/21/09   9:15:31 AM
          c16.indd   482
   515   516   517   518   519   520   521   522   523   524   525