测试代码执行速度

来源:互联网 发布:淘宝店家不退款怎么办 编辑:程序博客网 时间:2024/05/02 03:11


 

第一种

生成实例的时候开始初始化了,在你想要测试的code后面直接调用countTime()就行,然后在你需要的地方printOut就调用result();;方便..
还可以测试总时间,把刷新的语句注释掉,就行...呵呵

PHP代码:

<?php
class TimeCount{
   var   
$baseTime;
   var   
$printMsg;
   var   
$pattern;
   var   
$printName;
  function
TimeCount($name){
  
$this->baseTime=microtime();
  
$this->printMsg=array();
  
$this->totalTime=0;
  
$this->pattern='^([^ ]+) (.+)';
  
$this->printName=$name;
  }
function
countTime($label){
$currentTime=microtime();
ereg($this->pattern,$currentTime,$c);
$cu=doubleval($c[2])+doubleval($c[1]);
ereg($this->pattern,$this->baseTime,$b);
$ba=doubleval($b[2])+doubleval($b[1]);
$diff=abs($cu-$ba);
$this->printMsg[]=sprintf("<br>%-20s %s s",$label,$diff);

/**
  *This assignment use to refresh the baseTime ;
  *When you needed to add the totalTime,Please remove the comments.
  *@default remove comments;
  */
  
$this->baseTime=$currentTime;
  }
function
result(){
echo
$this->printName;
foreach(
$this->printMsg as $v){
echo
$v;
  }
}
}
$timeTest=new TimeCount('Timing:');
for(
$i=0;$i<99999;$i++){}
$timeTest->countTime("The First Circle:");
for(
$i=0;$i<99999;$i++){}
$timeTest->countTime("The Second Circle:");
$timeTest->result();
?>

第二种


function getmicrotime()
{
   list($usec, $sec) = explode(" ",microtime());
   return ((double)$usec + (double)$sec);
}
$start = getmicrotime();
//其它程序//-->
$end = getmicrotime();
$d   =$end-$start;
echo "程序执行了".$d;