Zend - The PHP Company




Utilities

Add Code


ProTimer Class  

Type: application
Added by: rhull627
Entered: 04/08/2004
Last modified: 08/12/2003
Rating: - (fewer than 3 votes)
Views: 3514
A lightweight timing class to be used for profiling your code. One member variable, 3 member functions (incl. constructor). Also includes a footer file so that you may include 'ProTimerFooter.inc'; in order to get a table that displays the profiling info.


----------- ProTimer.inc -------------
<?
if(defined('__PROTIMER.INC'))
  return;
else
  
define('__PROTIMER.INC'1);

class 
ProTimer
{
  var 
$start;

  function 
ProTimer() 
  { 
    
$this->start $this->GetMicrotime(); 
  }

  function 
GetMicrotime()
  {
    
$tmp_ary explode(' 'microtime());
    return((float)
$tmp_ary[1] + (float)$tmp_ary[0]);
  }

  
// this function returns the elapsed time and resets the timer
  // therefore, the elapsed time is measured since instantiation or
  // the last time ReadTimer was called
  
function ReadTimer($decimals 4
  {
    
$end $this->GetMicrotime();
    
$start $this->start;
    
$decimals intval($decimals);
    if (
$decimals 8)
      
$decimals 8;
    if (
$decimals 0)
      
$decimals 0;
    
$this->start $this->GetMicrotime();
    return 
number_format($end $start$decimals);
  }

?>

--------- ProTimerFooter.inc --------------
<?
// this footer assumes that you have stored your various elapsed times
// in an associative array name $ProTimes
if(!empty($ProTimes))
{
  print 
'<table><th>Code Section</th><th>Elapsed Time</th>';
  foreach(
$ProTimes as $label => $time)
    print 
"<tr><td>$label</td><td>$time s</td></tr>n";
  print 
'</table>';
}
?>


Usage Example


/* Usage Example */
include 'ProTimer.inc';

// start the overall timer
$o_timer = new ProTimer();

// start the section timer
$s_timer = new ProTimer();

for($i = 0; $i <= 9999; $i++)
  $my_ary[$i] = $i * 2;

// get the elapsed time, reset $s_timer
$ProTimes['for-10000'] = $s_timer->ReadTimer();

foreach($my_ary as $index => $value)
  $value /= 2;

// get the elapsed time, reset $s_timer
$ProTimes['foreach'] = $s_timer->ReadTimer();

// get the total elapsed time, reset $o_timer
$ProTimes['total'] = $o_timer->ReadTimer();

include 'ProTimerFooter.inc'; 


Rate This Script





Search



This Category All Categories