您的位置:首页 > 编程语言 > PHP开发

计算php代码执行时间长短的类(精确到毫秒)

2018-01-16 09:57 561 查看
<?php

/**

 * PHP脚本执行时间计算

 */

class runtime

{

    var $StartTime = 0;

    var $StopTime = 0;

    function get_microtime()

    {

        list($usec, $sec) = explode(' ', microtime());
//var_dump($usec);var_dump($sec);

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

        //毫秒
//$msec = $spent*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();

?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: