Skip to content

Instantly share code, notes, and snippets.

@kmddevdani
Last active August 8, 2018 01:57
Show Gist options
  • Save kmddevdani/47dc27877d4ed628d90f2641d3a2b8cd to your computer and use it in GitHub Desktop.
Save kmddevdani/47dc27877d4ed628d90f2641d3a2b8cd to your computer and use it in GitHub Desktop.
measure and log code runtime
<?php
class my_class {
private $_timerId = [];
private function startTimer($timerId) {
$this->_timerId[$timerId]['start'] = microtime(true);
}
private function stopTimer($timerId) {
$this->_timerId[$timerId]['stop'] = microtime(true);
}
private function getDuration($timerId, $stopTimer = true) {
if ($stopTimer === true) {
$this->stopTimer($timerId);
$duration = $this->_timerId[$timerId]['stop'] - $this->_timerId[$timerId]['start'];
$this->_timerId[$timerId]['duration'] = $duration;
} else {
$duration = microtime(true) - $this->_timerId[$timerId]['start'];
}
return $duration;
}
private function logDuration($timerId, $stopTimer = true, $customMessage = '') {
$backtrace = debug_backtrace();
$line = $backtrace[0]['line'];
$msg = $timerId. ';' .$line.';'. $this->getDuration($timerId, $stopTimer) . ';' . $customMessage . PHP_EOL;
file_put_contents('performance.log', $msg, FILE_APPEND);
}
/**
* Example:
*/
public function demo1() {
$this->startTimer('total');
echo 'complicated operation';
$this->logDuration('total', false);
echo 'another complicated operation';
$this->logDuration('total);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment