2010-11-01 157 views
6

我有可能吗?例如 。如果我想测试str_replace()是否比preg_replace()更快?计算运行某个功能所需的时间

+0

可能重复[是否存在PHP函数(或每个任务)性能/基准测试?](http://stackoverflow.com/questions/2530610/does-a-php-per-function-or -per-task-performance-benchmark-reference-exist) – 2010-11-01 11:09:53

+0

对不起,忽略重复,我以为基准服务提供了他们使用的源代码,但他们没有。 – 2010-11-01 11:10:59

+1

你想为Zend_Debugger或XDebug这样的分析器。请参阅http://stackoverflow.com/search?q=profile+php+script – Gordon 2010-11-01 11:17:01

回答

13

你可以在你的脚本10000次(或更多)运行在同一行,并使用microtime(true)告诉它花了时间:

microtime()

+1

+1这是标准方法。 (a)你得到一个可测量的差值,(b)所以你可以在一次和另一次之间过滤掉速度差异。 – Spudley 2010-11-01 11:15:54

+0

谢谢!似乎我提到的2个函数几乎没有区别:) str_replace似乎只是有点更快有时 – Alex 2010-11-01 11:27:04

+0

我不是很确定,但是解释器有一个优化器,可以发现你的循环可以优化,因为没有变量在循环迭代中改变。因此,更好的方法是使用XDebug之类的代码分析器 – seriyPS 2010-11-01 12:21:51

25

最简单的办法:

$time = microtime(true); // time in Microseconds 

// Your code here 

echo (microtime(true) - $time) . ' elapsed'; 

硬(呃)的方式: 使用代码分析器来查看你的方法需要多少时间。

6

我在this的线程中找到'bisko'的答案。

$ start = microtime(true);

为(...){ .... }

$端= microtime中(真);

echo($ end - $ start)。'秒;

for循环可以替换为任何你想要的时间。