前言
本文介紹的是利用php/221643.html">php記錄代碼運行時間測量的相關內容,分享給大家供大家參考學習。一般在要求性能的代碼中, 會加入測試代碼進行計算。不過每次都要寫microtime, end – start 未必太麻煩了, 所以簡單的寫了一個類去搞,下面來看看詳細的介紹:
示例代碼
class TimeCost{ private $cost = array(); private $record = array(); private $scale = 6; public function __construct($scale = 6) { $this->cost = array(); $this->record = array(); $this->scale = $scale; } public function __toString() { return $this->getString(); } /** * start to cal time. * * @param mixed $key */ public function addCost($key) { $this->cost[$key] = microtime(true); } /** * stop to cal time. * * @param mixed $key */ public function closeCost($key) { $cost = bcsub(microtime(true), $this->cost[$key], $this->scale); if (in_array($key, array_keys($this->record))) { $this->record[$key] = bcadd($cost, $this->record[$key], $this->scale); } else { $this->record[$key] = $cost; } return $cost; } public function getString($key = null) { if ($key) { return "{$key}[{$this->record[$key]}]"; } $str = ''; foreach ($this->record as $k => $v) { $str .= "{$k}[{$v}]"; } return $str; }}用法
$obj = new TimeCost();$token = 'test_a';$obj->addCost($token);some_code();$obj->closeCost($token);$reslut = $obj->getString($token);
說明
1、時間精度: 默認是保留了6位, 已經足夠了, 想要更高精度, 可以在new對象的時候指定$scale參數
2、token: token是為了表示某段代碼, 對應的結果會以key(token), value的形式寫入到record數組中。
所以用一個token多次進行addCost和closeClost的結果會進行累積。
3、getString: 傳遞token則返回token對應的結果, 默認會將record中的所有結果拼接返回。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對VeVb武林網的支持。
新聞熱點
疑難解答