2011-01-25 40 views
1

我使用它像这样尝试的CPU使用率:PHP - 使用microtime中()测量功能/代码块

$now = microtime(true); 
// cpu expensive code here 
echo microtime(true) - $now; 

,但不管我这些语句之间输入什么密码,我alwasy得到几乎相同结果,类似3.0994415283203E-6

我在做什么错?

+1

尝试放入一个`sleep(5);`调用并确保结果改变。时间应至少五秒钟。看起来好像是 – 2011-01-25 01:32:12

+0

。我得到了`4.9997820854187` – Alex 2011-01-25 01:34:12

+9

哇! PHP很快!它在5秒内评估“睡眠(5)”; – Joel 2011-01-25 01:37:35

回答

6

更好的解决方案。运行代码多次来平均操作:

$runs = 500; 

$start = microtime(true); 
for ($i = 0; $i < $runs; $i++) { 
    //cpu expensive code here 
} 
$end = microtime(true); 
$elapsed = number_format($end - $start, 4); 
$one = number_format(($end - $start)/500, 7); 
echo "500 runs in $elapsed seconds, average of $one seconds per call"; 
3

3.0994415283203E-6相当于0.0000030994415283203

E-6告诉你将小数点左移六位。 E+6意味着相反。正如@deceze所说,这被称为科学记数法。

如果您正在进行性能测试,最好将代码放入100000左右的迭代循环中,然后将得到的时间除以100000。这样您可以获得更精确的平均值。

1

你没有做错任何事,只是你计时的代码真的只需要几分之一秒的时间来运行。

如果你想证明它,sleep几秒钟。

1

看起来你正在使用microtime()没有可选参数,但你说你的,所以我不是100%肯定。

是什么,它的输出:

$now = microtime(true); 
sleep(1); 
echo microtime(true) - $now; 
0

PHP总是让我感到吃惊与它的速度有多快。你的代码似乎是正确的。也许你的代码真的只需要3毫秒。

你可以尝试做一个长环,这样的事情:

$x=0; 
while ($x<1000000) 
    { 
    $x++; 
    } 

添加您的计时器这里面的代码。对我来说,循环100万次通常需要大约1/2秒。看看这是否会改变你的时间。