key) 獨立計時microtime)<?php
class Timer {
private $_start = [];
private $_end = [];
private $_default_key = 'Timer';
private $_prefix = 'Timer_';
public function start($key = '') {
$flag = $this->_getKey($key);
$this->_start[$flag] = $this->_getMicrotime();
}
public function end($key = '') {
$flag = $this->_getKey($key);
$this->_end[$flag] = $this->_getMicrotime();
}
public function getTime($key = '') {
$flag = $this->_getKey($key);
if (isset($this->_end[$flag]) && isset($this->_start[$flag])) {
return (float)($this->_end[$flag] - $this->_start[$flag]);
}
return 0;
}
public function printTime($key = '') {
$flag = $this->_getKey($key);
$label = $key === '' ? '' : $key . ' ';
printf("%srun time %.4f ms\n", $label, $this->getTime($key) * 1000);
}
private function _getKey($key = '') {
return $key === '' ? $this->_default_key : $this->_prefix . $key;
}
private function _getMicrotime() {
list($usec, $sec) = explode(' ', microtime());
return (float)$usec + (float)$sec;
}
}
?>
<?php
$timer = new Timer();
// 整體頁面計時
$timer->start();
// ... 業務邏輯 ...
$timer->end();
$timer->printTime(); // Timer run time 12.3456 ms
// 區塊計時
$timer->start('db_query');
// ... 資料庫查詢 ...
$timer->end('db_query');
$timer->printTime('db_query'); // Timer_db_query run time 5.6789 ms
?>
輕量、無依賴,適合性能分析與瓶頸定位。