写了一个类用来测试目标函数的执行时间。以下是类的定义代码:
复制代码 代码如下:
class EfficiencyTester {
private $testTimes = 1000;
private function getTime($timeModel = 'MS') {
if ($timeModel == 'MS') {
return microtime();
} else if ($timeModel == 'S') {
return time();
} else {
return microtime();
}
}
public function testonce($functionName, $timeModel = 'MS') {
$startMicroTime = $this->getTime($timeModel);
$functionName();
$endMicroTime = $this->getTime($timeModel);
$costMicroTime = $endMicroTime - $startMicroTime;
return $costMicroTime;
}
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() 函数中的判断占用了一部分时间。



