Jquery中文网 www.jquerycn.cn
Jquery中文网 >  脚本编程  >  php  >  正文 php获取目标函数执行时间

php获取目标函数执行时间

发布时间:2018-01-22   编辑:www.jquerycn.cn
如何用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');
?>
 

一开始直接使用 microtime() 获取时间的,后来考虑到如果想获得单位是秒的运行时间,这样写就不够多态了,然后就写了一个getTime() 的函数来获取不同单位的时间戳。
如此貌似目标函数的运行时间变长了,可能是因为 getTime() 函数中的判断占用了一部分时间。

您可能感兴趣的文章:
php获取目标函数执行时间的实例代码
php获取函数执行时间的简单例子
计算php脚本执行时间的示例代码
php获取目标函数执行时间
php 获取今日、昨日、上周、本月的起始与结束时间戳
php 文件系统处理 fopen
php 自动更新时间(动态显示时间到页面上)
【PHP学习】新手必备PHP常用函数大集合
php 时间日期函数
php用于页面执行时间的类

关键词: php函数  执行时间   
[关闭]