-
- /**
- * class EfficiencyTester
- * Efficiency tester, test the running time of functions
- * @version 1.0 2013.04.13
- * @author Kross
- */
- class EfficiencyTester {
- /**
- * var $testTimes
- * Number of tests
- */
- private $testTimes = 1000;
- /**
- * function getTime()
- * Get the timestamp according to the time mode
- * @param $timeModel time mode, default: microseconds
- * @return int timestamp
- */
- private function getTime($timeModel = 'MS') {
- if ($timeModel == 'MS') {
- return microtime();
- } else if ($timeModel == 'S') {
- return time();
- } else {
- return microtime();
- }
- }
- /**
- * function testOnce()
- * Test the target function once and return the running time
- * @param $functionName Target function name
- * @param $timeModel Time mode, default: microseconds
- * @return double The time for the target function to run once ( Very random)
- */
- public function testOnce($functionName, $timeModel = 'MS') {
- $startMicroTime = $this->getTime($timeModel);
- $functionName();
- $endMicroTime = $this->getTime($timeModel);
- $costMicroTime = $endMicroTime - $startMicroTime;
- return $costMicroTime;
- }
- /**
- * function test()
- * Test the target function multiple times and return the running time (average)
- * @param $functionName Target function name
- * @param $timeModel Time mode, default: microseconds
- * @return double Target function Running time
- */
- public function test($functionName, $timeModel = 'MS') {
- $totalMicroTimes = 0;
- for ($i = 1; $i <= $this->testTimes; $i++) {
- $totalMicroTimes += $this->testOnce($functionName);
- }
- return $totalMicroTimes / $this->testTimes;
- }
- }
- ?>
复制代码
测试代码:
-
- require_once('../class/EfficiencyTester.class.php');
- $e = new EfficiencyTester();
- echo $e->test('rand');
- ?>
-
复制代码
一开始直接使用 microtime() 获取时间的,后来考虑到如果想获得单位是秒的运行时间,这样写就不够多态了,然后就写了一个getTime() 的函数来获取不同单位的时间戳。
如此貌似目标函数的运行时间变长了,可能是因为 getTime() 函数中的判断占用了一部分时间。
|