PHP記錄代碼已耗用時間

來源:互聯網
上載者:User

代碼已耗用時間測量

一般在要求效能的代碼中, 會加入測試代碼進行計算。

不過每次都要寫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);

說明

  • 時間精度: 預設是保留了6位, 已經足夠了, 想要更高精度, 可以在new對象的時候指定$scale參數

  • token: token是為了表示某段代碼, 對應的結果會以key(token), value的形式寫入到record數組中。

    所以用一個token多次進行addCost和closeClost的結果會進行累積。

  • getString: 傳遞token則返回token對應的結果, 預設會將record中的所有結果拼接返回。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.