php擷取目標函數執行時間樣本

來源:互聯網
上載者:User

 這篇文章主要介紹了php擷取目標函數執行時間樣本,需要的朋友可以參考下

寫了一個類用來測試目標函數的執行時間。以下是類的定義代碼:  代碼如下:<?php/** * class EfficiencyTester * 效率測試器,測試函數的已耗用時間 * @version 1.0 2013.04.13 * @author Kross */class EfficiencyTester {        /**     * var $testTimes     * 測試的次數      */    private $testTimes = 1000;     /**     * function getTime()     * 根據時間模式,擷取時間戳記     * @param $timeModel 時間模式,預設:微秒     * @return int 時間戳記     */    private function getTime($timeModel = 'MS') {        if ($timeModel == 'MS') {            return microtime();        } else if ($timeModel == 'S') {            return time();        } else {            return microtime();        }    }    /**     * function testOnce()     * 測試目標函數一次,返回已耗用時間     * @param $functionName 目標函數名     * @param $timeModel 時間模式,預設:微秒     * @return double 目標函數運行一次的時間(很隨機)     */    public function testOnce($functionName, $timeModel = 'MS') {                $startMicroTime = $this->getTime($timeModel);        $functionName();        $endMicroTime = $this->getTime($timeModel);         $costMicroTime = $endMicroTime - $startMicroTime;         return $costMicroTime;    }    /**    * function test()    * 測試目標函數多次,返回已耗用時間(平均值)    * @param $functionName 目標函數名    * @param $timeModel 時間模式,預設:微秒    * @return double 目標函數啟動並執行時間    */    public function test($functionName, $timeModel = 'MS') {        $totalMicroTimes = 0;        for ($i = 1; $i <= $this->testTimes; $i++) {            $totalMicroTimes += $this->testOnce($functionName);        }        return $totalMicroTimes / $this->testTimes;    }}?>   以下是類的測試代碼:  代碼如下:<?phprequire_once('../class/EfficiencyTester.class.php');$e = new EfficiencyTester();echo $e->test('rand');?>  一開始我是直接使用 microtime() 擷取時間的,後來考慮到如果想獲得單位是秒的已耗用時間,這樣寫就不夠多態了,然後我就寫了一個getTime() 的函數來擷取不同單位的時間戳記,不過這樣,貌似目標函數的已耗用時間變長了,可能是因為 getTime() 函數中的判斷佔用了一部分時間。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.