PHP计算脚本执行时间类

来源:互联网 发布:linux中sleep函数 编辑:程序博客网 时间:2024/05/22 14:23

1.优化代码的时候,脚本的执行时间是一个很重要的考量方式,那么如何用PHP来实现计算PHP脚本的运行时间呢?

下面推荐给大家一个很好用得类.

runtime.class.php

/**
 * PHP脚本执行时间计算
 */
class runtime
{
    var $StartTime = 0;
    var $StopTime = 0;


    function get_microtime()
    {
        list($usec, $sec) = explode(' ', microtime());
        return ((float)$usec + (float)$sec);
    }


    function start()
    {
        $this->StartTime = $this->get_microtime();
    }


    function stop()
    {
        $this->StopTime = $this->get_microtime();
    }


    function spent($echo=false,$title='')
    {
        $spent = sprintf('%.4f',round(($this->StopTime - $this->StartTime) * 1000, 1)/1000);
        if($echo){
            echo  $title."执行时间:{$spent}秒<br/>";
        }else{
            return $spent;
        }
    }
    function clear()
    {
        $this->StartTime = 0;
        $this->StopTime = 0;
    }


}


测试代码:

#测试脚本代码
$runtime= new runtime;
$runtime->start();
$a = 0;
for($i=0; $i<100000; $i++)
{
    $a *= $i;
}
$runtime->stop();


$spent_time = $runtime->spent($echo=true, '测试脚本');


$runtime->clear();


测试结果:


1 0