Monday, January 29, 2007

PHP Timer Class

Wrote a PHP Timer class this afternoon that might come in handy here and there for anyone developing PHP scripts. It's really simple actually, but powerful enough to be used just about anywhere you would need to measure time of script block execution.

Usage is simple:

$t1 = new Timer("mytimer");
.. (perform some code) ..
$t1->stop();
$t1->display();

You can also create any amount of timers and Timer::dump() them at the end of the script for a nice overview.

There's no better way on Blogger to post code like this, so it'll have to do for now:


<?
/*
 * Simple Timer Class
 *
 * Author: Mattias Nilsson (mrorigo@gmail.com)
 * Licenced under GPL. No warranties implied or given. 
 * Use at your own risk.
 *
 * Usage:
 * $t = new Timer("myid1");
 * ...
 * $t->stop();
 * ...
 * $t->display();
 * OR
 * Timer::dump();
 *
 */
class Timer
{
  var 
$id false;
  var 
$start false;
  var 
$stop false;
  var 
$time false;

  static 
$_TIMERS;

  
/*
   * @param $id Unique ID for your timer
   * @param $autostart Set to false to avoid timer start
   */
  
function Timer($id$autostart=true)
  {
    
$this->id $id;
    
Timer::addTimer($this);
    if(
$autostart)
      
$this->start();
  }

  
/**
   * Start the timer
   */
  
function start()
  {
    
$this->start Timer::getmicrotime();
  }

  
/**
   * Stop the timer and calculate elapsed time.
   *
   * @return Elapsed time since timer start.
   */
  
function stop()
  {
    
$this->stop Timer::getmicrotime();
    
$this->time $this->stop $this->start;
    return 
$this->time;
  }

  
/* *
   * Displays the timer result. If the timer is still running, it is stopped.
   */
  
function display()
  {
    if(!
$this->time)
      
$this->stop();
    print 
"Timer: ".$this->id.": " sprintf("%.5fs",$this->time) . "\n";
  }


  
/**
   * Adds a timer to the global timers array
   *
   * @param $timer Timer to add
   */
  
static function addTimer($timer)
  {
    
Timer::$_TIMERS[$timer->id] = $timer;
  }

  
/**
   * Dump/display all timers
   */
  
static function dump()
  {
    
reset(Timer::$_TIMERS);
    while(list(
$id$timer) = each(Timer::$_TIMERS))
      
$timer->display();
  }

  
/**
   * @return The current system milliseconds time as a float (seconds.fraction)
   */
  
static function getmicrotime()
  { 
    list(
$usec$sec) = explode(" ",microtime()); 
    return ((float)
$usec + (float)$sec); 
  }

}
?>



No comments:

Post a Comment