时时商务社区

标题: php获取目标函数执行时间示例 [打印本页]

作者: 阿情    时间: 2018-2-14 06:00

            写了一个类用来测试目标函数的执行时间。以下是类的定义代码:
[U]复制代码[/U] 代码如下:
    /**
     * 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 testTimes; $i++) {
            $totalMicroTimes += $this->testOnce($functionName);
        }
        return $totalMicroTimes / $this->testTimes;
    }
}
?>
以下是类的测试代码:
[U]复制代码[/U] 代码如下:
test('rand');
?>
一开始我是直接使用 microtime() 获取时间的,后来考虑到如果想获得单位是秒的运行时间,这样写就不够多态了,然后我就写了一个getTime() 的函数来获取不同单位的时间戳,不过这样,貌似目标函数的运行时间变长了,可能是因为 getTime() 函数中的判断占用了一部分时间。
            
            
您可能感兴趣的文章:
  • PHP-Fcgi下PHP的执行时间设置方法
  • 显示程序执行时间php函数代码
  • php计算当前程序执行时间示例
  • PHP中使用微秒计算脚本执行时间例子
  • PHP间隔一段时间执行代码的方法
  • php计算函数执行时间的方法
  • php实现用于计算执行时间的类实例
            




    欢迎光临 时时商务社区 (http://bbs.4435.cn/) Powered by Discuz! X3.2