php獲取目標函數執(zhí)行時間示例
寫了一個類用來測試目標函數的執(zhí)行時間。以下是類的定義代碼:
<?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() 獲取時間的,后來考慮到如果想獲得單位是秒的運行時間,這樣寫就不夠多態(tài)了,然后我就寫了一個getTime() 的函數來獲取不同單位的時間戳,不過這樣,貌似目標函數的運行時間變長了,可能是因為 getTime() 函數中的判斷占用了一部分時間。
相關文章
PHPMailer ThinkPHP實現自動發(fā)送郵件功能
這篇文章主要為大家詳細介紹了PHPMailer ThinkPHP實現自動發(fā)送郵件功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-06-06單一index.php實現PHP任意層級文件夾遍歷(Zjmainstay原創(chuàng))
本程序實現了使用一個index.php文件來實現所有文件夾的遍歷效果,避免了需要無窮復制index.php至文件夾下才能實現的效果2012-07-07Thinkphp自定義美化success和error提示跳轉頁面代碼實例
這篇文章主要介紹了Thinkphp自定義美化success和error提示跳轉頁面代碼實例,有需要的同學可以直接借鑒文中代碼,可以增加頁面的美觀和友好程度2021-03-03CodeIgniter框架實現的整合Smarty引擎DEMO示例
這篇文章主要介紹了CodeIgniter框架實現的整合Smarty引擎DEMO,結合實例形式分析了CodeIgniter框架整合Smarty引擎的原理、操作步驟及相關實現技巧,需要的朋友可以參考下2019-03-03