虽然我是个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 
posted on 2011-11-15 00:17 
-274°C 阅读(2174) 
评论(0)  编辑  收藏  所属分类: 
PHP