set_time_limit(1200);
class PerformanceTest
{
private $time;
private $memory;
public function begin()
{
$this->time = $this->getTime();
$this->memory = $this->getMemory();
}
public function end()
{
$this->time = $this->getTime() - $this->time;
$this->time = round($this->time,23);//在这里才能格式化时间
$this->memory = $this->getMemory() - $this->memory;
$this->memory = $this->convert($this->memory);
echo "time:{$this->time}秒<br />";
echo "memory:{$this->memory}<br />";
return $this->time;
}
public function getSpentTime()
{
return $this->time;
}
public function getTime()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
public function getMemory()
{
return memory_get_usage();
}
public function convert(int $size)
{
if(!$size)
{
return '0 b';
}
$size = abs($size);
$unit=array('b','kb','mb','gb','tb','pb');
return @round($size/pow(1024,($i=floor(log($size,1024)))),2).' '.$unit[$i];
}
}
function poly(array $a,float $x,int $degree)
{
$result = $a[0];
$xpwr = $x;
for($i=1;$i<=$degree;$i++)
{
$result += $a[$i] * $xpwr;
$xpwr = $x * $xpwr;
}
return $result;
}
function poly2(array $a,float $x,int $degree)
{
$result = $a[0];
$xpwr = $x;
for($i=1;$i<=$degree;$i++)
{
$result = $result + $a[$i] * $xpwr;//效率低于+=
$xpwr = $x * $xpwr;
}
return $result;
}
function polyh(array $a,float $x,int $degree)
{
$result = $a[$degree];
for($i=$degree-1;$i>=0;$i--)
{
$result = $a[$i] + $x*$result;
}
return $result;
}
function buildData(int $len)
{
$ret = [];
if($len>0)
{
for($i=0;$i<$len;$i++)
{
$ret[] = randomFloat(0,100);
}
}
return $ret;
}
function randomFloat($min = 0, $max = 1)
{
return $min + mt_rand() / mt_getrandmax() * ($max - $min);
}
$a = new PerformanceTest();
$count = 10000;
$x = (double)randomFloat(0,100);
$v= buildData($count+1);
$cmp = 0;
$cmp2 = 0;
$loop=0;
Loop:
$a->begin();
poly($v,$x,$count);
$a->end();
$poly = $a->getSpentTime();
$a->begin();
polyh($v,$x,$count);
$a->end();
$polyh = $a->getSpentTime();
$a->begin();
poly2($v,$x,$count);
$a->end();
$poly2 = $a->getSpentTime();
if($polyh - $poly<0)
{
$cmp++;
}
if($poly2 - $poly <0)
{
$cmp2++;
}
$loop++;
if($loop < 1000)
{
goto Loop;
}
var_dump($cmp);
var_dump($cmp2);
/**
time:0秒
memory:0 b
time:0.0010001659393311秒
memory:0 b
time:0.00099992752075195秒
memory:0 b
time:0秒
memory:0 b
time:0.00099992752075195秒
memory:0 b
int(554) int(238)
**/
exit;