How to compare the execution time of PHP code blocks

How to compare the execution time of PHP code blocks?

Sometimes we want to test our code for efficiency and execution time by comparing it with other code. Here’s how you can compare two code blocks in PHP and decide which one is faster (helps in optimization of code).

$str = '1,2,3,4,';   //we will trim the trailing comma

$time = microtime(); $micro1 = explode(' ', $time);
echo "Started at $time\n";    //Note the starting time.

$str1 = (substr($str,-1) == ',') ? substr($str, 0, -1) : $str;

$time = microtime(); $micro2 = explode(' ', $time);
echo "Took ", bcsub($micro2[1],$micro1[1]), bcsub($micro2[0],$micro1[0],6)," secs\n";

$str2 = preg_replace("/,*$/", '', $str);

$time = microtime(); $micro3 = explode(' ', $time);
echo "Took ", bcsub($micro3[1],$micro2[1]), bcsub($micro3[0],$micro2[0],6)," secs\n";

Output:

It ran it a few times on command-line on my local computer and it gave,

D:\>php New9.php

Started at 0.59481000 1283787551

Took 00.000610 secs

Took 00.001064 secs

D:\>php New9.php

Started at 0.01657800 1283787594

Took 00.000658 secs

Took 00.001177 secs

D:\>php New9.php

Started at 0.29726000 1283787644

Took 00.000390 secs

Took 00.000557 secs

D:\>php New9.php

Started at 0.57921400 1283787650

Took 00.000614 secs

Took 00.001060 secs

D:\>php New9.php

Started at 0.68782700 1283787653

Took 00.000372 secs

Took 00.000497 secs

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>