国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > PHP > 正文

php獲取目標函數執行時間示例

2024-05-04 23:21:55
字體:
來源:轉載
供稿:網友

寫了一個類用來測試目標函數的執行時間。以下是類的定義代碼:

復制代碼 代碼如下:


<?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;
    }
}
?>

以下是類的測試代碼:

復制代碼 代碼如下:


<?php
require_once('../class/EfficiencyTester.class.php');
$e = new EfficiencyTester();
echo $e->test('rand');
?>

一開始我是直接使用 microtime() 獲取時間的,后來考慮到如果想獲得單位是秒的運行時間,這樣寫就不夠多態了,然后我就寫了一個getTime() 的函數來獲取不同單位的時間戳,不過這樣,貌似目標函數的運行時間變長了,可能是因為 getTime() 函數中的判斷占用了一部分時間。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 武乡县| 澄迈县| 海安县| 新昌县| 潼南县| 大石桥市| 涪陵区| 东台市| 天峨县| 罗定市| 富民县| 峨眉山市| 攀枝花市| 三门峡市| 永和县| 嘉鱼县| 桐城市| 南投市| 屯昌县| 云和县| 双牌县| 三都| 南川市| 清涧县| 山西省| 西华县| 乌什县| 青龙| 大埔区| 汉阴县| 饶平县| 潢川县| 温州市| 疏附县| 濮阳市| 福海县| 朔州市| 乌兰察布市| 喀喇沁旗| 靖西县| 德江县|