這篇文章主要介紹了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() 函數中的判斷佔用了一部分時間。