start( 'section 1' ); // $sw->start( 'section 2' ); // $sw->start( 'section n...' ); // $sw->stop(); // echo 'Stopwatch timings: ' . $sw->toString(); // requires PHP5 class Stopwatch{ private $marks = array(); // array of timestamp marks private $sections = array(); // array of times between each mark (calculated when stop() is called) private $total = 0; // total time for all sections // start a new named stopwatch section. use this to start the stopwatch, and call repeatedly for each new section public function start( $section ){ $this->marks[ $section ] = microtime( true ); } // call when the end of the final section is reached. closes off the last session, and calculates session times public function stop(){ $this->start( 'END' ); $previousSection = false; foreach( $this->marks as $section => $mark ) { if( $previousSection !== false ) { $elapsed = $mark - $this->marks[ $previousSection ]; $this->sections[ $previousSection ] = $elapsed; $this->total += $elapsed; } $previousSection = $section; } } // get total time public function getTotal(){ return $this->total; } // get time for a particular section public function getTime( $name ){ return array_key_exists( $name, $this->sections ) ? $this->sections[ $name ] : 0; } // return summary of all sections, as a string public function toString(){ $ret = ''; foreach( $this->sections as $section => $time ) $ret .= "$section:$time "; $ret .= 'TOTAL:' . $this->getTotal(); return $ret; } } ?>