zoukankan      html  css  js  c++  java
  • php获取目标函数执行时间

      几个星期以前,写了一个正则从新浪网首页获取所有的链接地址,存入数组print_r()出来,大约是1400条记录。只是print_r()的话,大概花费了3-4秒的时间,后来,我又加上写入数据库的函数,把取得的url(href中的内容)和链接名(<a></a>之间的内容)写入数据库中,那个php一执行就没有响应,直到页面返回超过最大执行时间的警告。这时,我才真正的体会到搜索引擎从互联网上获取内容的艰辛。

      因此,今天写了一个类,取名为EfficiencyTester,用来测试目标函数的执行时间。贴上代码,希望能与网上的众多大神交流。

      以下是类的定义代码:

    <?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() 函数中的判断占用了一部分时间。如果各位看官有什么好的主意,希望能给我留言,让我学习学习~O(∩_∩)O

  • 相关阅读:
    JWT攻击
    CTF中的RSA 算法
    PHP反序列化字符逃逸
    记一次代码审计 [De1CTF 2019]SSRF Me
    BUU 思路记录(更新中
    日志注入漏洞
    docker 常用命令
    [HITCON 2017]SSRFme
    xss 19道题目
    BUUCTF之[EIS 2019]EzPOP&BUUCTF[2020 新春红包题]1 web
  • 原文地址:https://www.cnblogs.com/kross/p/3018668.html
Copyright © 2011-2022 走看看