多个PHP页面运行是相互之间是不会干扰的,所以开始运行时取microtime(),结束时再取,相减就是运行时间。

解决方案 »

  1.   

    同意LostinDark(Lost_in_Dark),大多数的PHP程序也是这么计算脚本执行时间的。
      

  2.   

    我的意思是microtime()获取的是系统当前时间,两次相减的时间差未必就是页面自身独自运行所占有的CPU时间。
    尤其是当PHP页面进行一些耗时的处理(如访问数据库)时,时间占用还是比较大的。
    由于服务器处理脚本时是多线程的,即可以同时运行多个脚本。各个脚本自然是轮流地被分配到CPU时间片,那么计算单个PHP脚本的运行时间采用以上方式就不那么准确了。
    难道服务器会因为一个PHP脚本访问数据库时延时而暂停或者不运行其它PHP脚本吗?那样不就编程单线程了吗?
      

  3.   

    如果如楼上所说的那样,使用microtime()来计算页面运行时间的话,我遇到的以下问题就难以解释了。同样一个PHP页面(访问数据库的),在本机调试和在服务器上运行时,本机使用的时间(通过microtime计算)明显短于服务器。我对此情况的解释是因为服务器是虚拟主机,许多脚本同时运行,且数据库比较忙,所以造成运行时间延长。但这并不是我的那个PHP脚本本身的问题,所以显示比实际长的运行时间显然不正确。
    另外,经过测试,还发现显示的时间和网络速度有关。当网络繁忙,导致页面显示速度较慢时,显示的运行时间也会延长。
      

  4.   

    服务的执行比较久也有可能是因为服务器的硬件问题呀!
    硬盘转速慢
    cpu执行速度慢
    内存太小
    用cgi模式运行
    等等呀!
      

  5.   

    服务器的问题会导致运行速度慢,但我用的是ISP的虚拟主机啊,再怎么样都应该比我的台式机好吧
    而且如果在半夜网络空闲的时候测试,速度明显地快。这更说明是服务器繁忙造成页面运行时间延长的结果啊
      

  6.   

    <%
    class timer { 
        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 = doubleval($StartMicro) + $StartSecond; 
                $stop  = doubleval($StopMicro) + $StopSecond; 
                $this->TimeSpent = $stop - $start; 
                return substr($this->TimeSpent,0,8)."sec"; 
            } 
        }  // end function spent(); } //end class timer; //这里是一个简单的例子: 
        $timer = new timer; 
        $timer->start(); 
        $temp=0; 
        for($i=0;$i<1000;$i++) for($j=0;$j<$i;$j++) $temp ++; 
        $timer->stop(); 
        echo "run $temp times,time ".$timer->spent(); 
    %>