PHP實(shí)現(xiàn)記錄代碼運(yùn)行時(shí)間封裝類實(shí)例教程
前言
本文介紹的是利用php記錄代碼運(yùn)行時(shí)間測量的相關(guān)內(nèi)容,分享給大家供大家參考學(xué)習(xí)。一般在要求性能的代碼中, 會(huì)加入測試代碼進(jìn)行計(jì)算。不過每次都要寫microtime, end – start 未必太麻煩了, 所以簡單的寫了一個(gè)類去搞,下面來看看詳細(xì)的介紹:
示例代碼
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、時(shí)間精度: 默認(rèn)是保留了6位, 已經(jīng)足夠了, 想要更高精度, 可以在new對(duì)象的時(shí)候指定$scale參數(shù)
2、token: token是為了表示某段代碼, 對(duì)應(yīng)的結(jié)果會(huì)以key(token), value的形式寫入到record數(shù)組中。
所以用一個(gè)token多次進(jìn)行addCost和closeClost的結(jié)果會(huì)進(jìn)行累積。
3、getString: 傳遞token則返回token對(duì)應(yīng)的結(jié)果, 默認(rèn)會(huì)將record中的所有結(jié)果拼接返回。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
相關(guān)文章
JavaScript?數(shù)據(jù)結(jié)構(gòu)之集合創(chuàng)建(2)
這篇文章主要介紹了JavaScript?數(shù)據(jù)結(jié)構(gòu)之集合創(chuàng)建,上一篇我們介紹了什么是集合,并且手動(dòng)實(shí)現(xiàn)了一個(gè)集合的類,本篇基于上篇內(nèi)容繼續(xù)深入介紹需要的小伙伴可以參考一下2022-04-04
JS Array.from()將偽數(shù)組轉(zhuǎn)換成數(shù)組的方法示例
這篇文章主要介紹了JS Array.from()將偽數(shù)組轉(zhuǎn)換成數(shù)組的方法示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03
解析offsetHeight,clientHeight,scrollHeight之間的區(qū)別
這篇文章主要是對(duì)offsetHeight,clientHeight,scrollHeight之間的區(qū)別進(jìn)行了詳細(xì)介紹,需要的朋友可以過來參考下,希望對(duì)大家有所幫助2013-11-11
Ionic 2 實(shí)現(xiàn)列表滑動(dòng)刪除按鈕的方法
這篇教程將展示如何使用Ionic2添加一個(gè)簡單的刪除按鈕到列表,當(dāng)用戶滑動(dòng)列表項(xiàng)到左邊的時(shí)候。這是一個(gè)處理刪除列表數(shù)據(jù)時(shí)候常用的模式,具體內(nèi)容大家通過本文學(xué)習(xí)吧2017-01-01
JavaScript實(shí)現(xiàn)網(wǎng)頁帶動(dòng)畫返回頂部的方法詳解
這篇文章主要為大家詳細(xì)介紹了如何利用JavaScript實(shí)現(xiàn)網(wǎng)頁帶動(dòng)畫返回頂部的效果,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2022-08-08
小程序?qū)崿F(xiàn)發(fā)表評(píng)論功能
這篇文章主要為大家詳細(xì)介紹了小程序?qū)崿F(xiàn)發(fā)表評(píng)論功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-07-07

