Wednesday 19 November 2014

PHP Timer Script

This is the only PHP script that I wrote and use nearly everyday but never published! My stopwatch / timer script… I use it to test, benchmark most of the other scripts I write.
Sometimes webmasters use something similar to show you Page Generation times at the bottom of a web page; not unlike what I have done myself at the bottom of this page e.g.
1
Vilitas.com created this page in 0.105253 seconds.
So, not only is this Timer / Stopwatch code good for figuring out how efficiently your code runs, it also helps to add to your page content!

PHP Page Generation / Timer script

Copy the entire code below and save it as stopwatch.php if you want to use it as a benchmarking tool while you test your different PHP scripts.

<?php
 
//  Filename: stopwatch.php
//  =======================
 
//  Start TIMER
//  -----------
$stimer = explode( ' ', microtime() );
$stimer = $stimer[1] + $stimer[0];
//  -----------
 
/* ------------------------------------- */
//  Add your PHP script and/or content here
/* ------------------------------------- */
 
//  End TIMER
//  ---------
$etimer = explode( ' ', microtime() );
$etimer = $etimer[1] + $etimer[0];
echo '<p style="margin:auto; text-align:center">';
printf( "Script timer: <b>%f</b> seconds.", ($etimer-$stimer) );
echo '</p></body></html>';
//  ---------
If you want to use it as a Page Generation Time tool, you can just add your content where it says

/* ------------------------------------- */
//  Add your PHP script and/or content here
/* ------------------------------------- */
and rename the file… but that’s not very smart, is it?

Including Page Generation times on all your web pages

The popular way to do it actually is to add 2 parts of this script into 2 different PHP include files:
  • header.php
  • footer.php
and then just include the 2 files (header.php & footer.php) on every web page your web site serves!

Sample header.php / footer.php

header.php


<?php
//  Start TIMER
//  -----------
$stimer = explode( ' ', microtime() );
$stimer = $stimer[1] + $stimer[0];
//  -----------
//  SOME MORE HEADER CONTENT, IF ANY...
//

footer.php


<?php
//  SOME MORE CLOSING/FOOTER CONTENT, IF ANY...
//
//  End TIMER
//  ---------
$etimer = explode( ' ', microtime() );
$etimer = $etimer[1] + $etimer[0];
echo '<p style="margin:auto; text-align:center">';
printf( "Script timer: <b>%f</b> seconds.", ($etimer-$stimer) );
echo '</p></body></html>';
//  ---------

No comments:

Post a Comment