I that possible?
for eg. if I want to test if str_replace()
is faster that preg_replace()
?
Asked
Active
Viewed 1.8k times
9
-
possible duplicate of [Does a PHP per-function (or per-task) performance / benchmark reference exist?](http://stackoverflow.com/questions/2530610/does-a-php-per-function-or-per-task-performance-benchmark-reference-exist) – Pekka Nov 01 '10 at 11:09
-
Sorry, disregard the duplicate, I thought the benchmark services provided the source code they use, but they don't. – Pekka Nov 01 '10 at 11:10
-
1You want a profiler like Zend_Debugger or XDebug for that. See http://stackoverflow.com/search?q=profile+php+script – Gordon Nov 01 '10 at 11:17
3 Answers
30
The easy way:
$time = microtime(true); // time in Microseconds
// Your code here
echo (microtime(true) - $time) . ' elapsed';
The hard(er) way: Use a code profiler to see exactly how much time your methods will take.

TheGrandWazoo
- 2,879
- 1
- 17
- 15
15
You can run the same line 10,000 times (or more) in your script, and use microtime(true)
to tell the time it took.
Reference: microtime()

nonopolarity
- 146,324
- 131
- 460
- 740
-
1+1 This is the standard method. It's important to do it a large number of times (ie in a loop) so that (a) you get a measurable difference, and (b) so you can filter out variances in speed between one run and another. – Spudley Nov 01 '10 at 11:15
-
thanks! it seems there's almost no difference between the 2 functions I mentioned :) str_replace seems just a little faster sometimes – Alex Nov 01 '10 at 11:27
-
I'm not absolutely sure, but interpreter's has an optimizer's, that can find that you loop can be optimized, because there is no variables changed in loop iterations. So, better way is to use code-profilers like XDebug – seriyPS Nov 01 '10 at 12:21
7
I found this answer by 'bisko' in this thread.
$start = microtime(true);
for (...) { .... }
$end = microtime(true);
echo ($end - $start).' seconds';
The for-loop can be replaced by whatever you want to time.

Community
- 1
- 1

TinkerTank
- 5,685
- 2
- 32
- 41