這篇文章給大家分享的是有關PHP如何實現記錄代碼運行時間封裝類的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
示例代碼
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中的所有結果拼接返回。
感謝各位的閱讀!關于“PHP如何實現記錄代碼運行時間封裝類”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。