這篇文章給大家介紹使用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;
}
}
?>
以下是類的測試代碼:
復制代碼 代碼如下:
<?php
require_once('../class/EfficiencyTester.class.php');
$e = new EfficiencyTester();
echo $e->test('rand');
?>
關于使用php怎么獲取目標函數的執行時間就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。