Last active
August 8, 2018 01:57
-
-
Save kmddevdani/47dc27877d4ed628d90f2641d3a2b8cd to your computer and use it in GitHub Desktop.
measure and log code runtime
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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