Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate the time needed to run a certain function

I that possible? for eg. if I want to test if str_replace() is faster that preg_replace() ?

like image 269
Alex Avatar asked Nov 01 '10 11:11

Alex


3 Answers

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.

like image 193
TheGrandWazoo Avatar answered Sep 23 '22 01:09

TheGrandWazoo


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()

like image 37
nonopolarity Avatar answered Sep 23 '22 01:09

nonopolarity


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.

like image 20
TinkerTank Avatar answered Sep 22 '22 01:09

TinkerTank