教程集 www.jiaochengji.com
教程集 >  脚本编程  >  php  >  正文 PHP microtime用法点滴

PHP microtime用法点滴

发布时间:2014-12-14   编辑:jiaochengji.com
PHP microtime用法点滴

虽然我是个PHP新手,但是今天看到一段代码,忍不住修改了几行。
 

复制代码 代码如下:

<?php
class runTime {
    var $StartTime = 0;
    var $StopTime = 0;
    var $TimeSpent = 0;

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

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

    function spent() {
        if ($this->TimeSpent) {
            return $this->TimeSpent;
        } else {
            $StartMicro = substr($this->StartTime,0,10);
            $StartSecond = substr($this->StartTime,11,10);
            $StopMicro = substr($this->StopTime,0,10);
            $StopSecond = substr($this->StopTime,11,10);
            $start = floatval($StartMicro) + $StartSecond;
            $stop = floatval($StopMicro) + $StopSecond;
            $this->TimeSpent = $stop - $start;
            return round($this->TimeSpent,8);
        }
    } // end function
}

1、为什么说封装欠妥?
在使用过程中,我发现那几个类的属性,没必要作为var (public )形式出现,既然用了class,那么就遵照下面向对象的一些基本规则,这几个变量完全可以用private 访问控制。

2、microtime 用得不够好?
手册上关于microtime 的一些说明:

定义和用法
microtime() 函数返回当前 Unix 时间戳和微秒数。

如果调用时不带可选参数,本函数以 "msec sec" 的格式返回一个字符串,其中 sec 是自 Unix 纪元(0:00:00 January 1, 1970 GMT)起到现在的秒数,msec 是微秒部分。字符串的两部分都是以秒为单位返回的。

在PHP5 以上版本,是可以接受参数true,这样就能直接返回浮点数,而且效率会比现在这样做高不少。

下面是网上找到的一段小代码,可以做参考:
 

复制代码 代码如下:

<?php
function microtime_float3(){
    return microtime(true);
}

function microtime_float2(){
    if( PHP_VERSION > 5){
        return microtime(true);
    }else{
        list($usec, $sec) = explode(" ", microtime());
        return ((float)$usec + (float)$sec);
    }
}

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

function runtime($t1){
    return number_format((microtime_float() - $t1)*1000, 4).'ms';
}

$t1 = microtime_float();
for($i=0;$i<10000;$i++){
    microtime_float();
}
echo "microtime_float=====";
echo runtime($t1).'<br>';
$t1 = microtime(true);

for($i=0;$i<10000;$i++){
    microtime(true);
}
echo "microtime_true=====";
echo runtime($t1).'<br>';
$t1 = microtime(true);

for($i=0;$i<10000;$i++){
    microtime_float2();
}

echo "microtime_float2=====";
echo runtime($t1).'<br>';
$t1 = microtime(true);

for($i=0;$i<10000;$i++){
    microtime_float3();
}
echo "microtime_float3=====";
echo runtime($t1).'<br>';
?>

本机winxp运行结果:
microtime_float=====109.5631ms
microtime_true=====38.8160ms
microtime_float2=====52.7902ms
microtime_float3=====45.0699ms

Linux上运行结果:
microtime_float=====47.2510ms
microtime_true=====9.2051ms
microtime_float2=====16.3319ms
microtime_float3=====12.2800ms

您可能感兴趣的文章:
PHP microtime用法点滴
PHP函数microtime()时间戳的定义与用法
PHP microtime() 函数实例教程
photoshop设计一个水滴主题UI图标绘制教程
Photoshop利用蒙版和高斯模糊制作彩色透明水滴教程
PHP程序循环迭代中谨慎操作数据库
u盘怎么格式化 u盘无法格式化怎么办?
PHP计算页面执行时间的代码举例
有关php中的microtime相关知识的整理
PHP array_search 和 in_array 函数效率问题

[关闭]
~ ~