Wednesday, March 23, 2005

PHP: clock_code()

My take on the PHP script timer. First time I've found an ideal use for the STATIC variable type:

/* clock_code()
author: Tom Atwell (tatwell at jee mail dot com)
description: a neatly packaged script-timing function
reference: http://www.php.net/manual/en/function.microtime.php (Notes)
credit: edwardzyang at thewritingpot dot com, 14-Mar-2005 09:31
/************************************************************/
function clock_code($leader='clock_code()', $echo=TRUE, $unit='ms')
{

// personal version check -- disables in live server environment
if ( defined('VERSION') && (VERSION == 'live') ) {
return;
}

// current time
$cc_now = microtime(TRUE); /* float, in _seconds_ */

// declare static vars
static $CC_SPLIT, $CC_CALLS;

// define original start time
if ( !defined('CC_START') ) {
define('CC_START', $cc_now );
}

// declare internal variables
$cc_last = $CC_SPLIT; /* to calculate split time between calls */
$CC_CALLS++; /* increment counter */

// declare output variables
$output = '';
$div = '<div style="border:thin solid lime; margin:4px;">';
$p_calls = ' [clock_code() Call #' . $CC_CALLS . '] : ';


// vary according to unit selected
if ($unit === 's') {
$cc_now = $cc_now + time();
$malt = 1;
$round = 7;
} elseif ($unit === 'ms') {
$malt = 1000;
$round = 3;
} else {
trigger_error('Unsupported $unit value');
}


/* Stop the chronometer : return the amount of time since it was started,
in ms with a precision of 3 decimal places, and reset the start time.
We could factor the multiplication by 1000 (which converts seconds
into milliseconds) to save memory, but considering that floats can
reach e+308 but only carry 14 decimals, this is certainly more precise */

$cc_elapsed = round($cc_now * $malt - CC_START * $malt, $round);
$CC_SPLIT = $cc_elapsed;
$cc_stage = $CC_SPLIT - $cc_last;
$p_split = ' [SPLIT: ' . $cc_stage . ' ' . $unit . '] ';

// build output string
$output = $div . $leader . $p_calls . $cc_elapsed . ' ' . $unit;
$output .= '$p_split . '</div>';

// output
if ( ($CC_CALLS > 1) && $echo ) {
echo $output;
return;
} else {
return $output;
}

} /* end Fx clock_code */
/*******************************/


How to use:

<?php

clock_code();

// Do stuff;

clock_code('Do Stuff'); /* will return the time taken to "Do stuff" */

// Do more stuff

clock_code('Do More Stuff'); /* returns time taken to "Do more stuff" */

?>


How it looks:

Do Stuff [clock_code() Call #2] : 4.869 ms [SPLIT: 4.869 ms]
Do More Stuff [clock_code() Call #3] : 47.446 ms [SPLIT: 42.577 ms]


(Maybe I should rename this blog "A Flimsy PHPretext")

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home