使用php怎么获取目标函数的执行时间

这篇文章给大家介绍使用php怎么获取目标函数的执行时间,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

 代码如下:


<?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');
?>

关于使用php怎么获取目标函数的执行时间就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。