PHP封装类测试目标函数执行时间
编写了一个PHP类,旨在精确测算特定目标函数的运行耗时。以下是该类的具体定义代码:
复制代码 代码如下:
/** * 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; } } ?>
接下来展示该类的实际测试代码:
复制代码 代码如下:
起初直接使用 microtime() 获取时间,但考虑到若需以秒为单位统计运行时间,直接调用显得缺乏多态性。因此设计了 getTime() 方法来适配不同单位的时间戳需求。不过实测发现,这种设计似乎延长了目标函数的表观运行时间,原因可能是 getTime() 内部的判断逻辑消耗了部分时间。