Jimmy's Blog Jimmy Ruska's Blog
Benchmark your PHP with 3 lines of code Posted on Tuesday, February 12 2008
Learn to Play Songs by Ear: Ear Training

You already know there's multiple ways of working out the same problem, but how do you know which way is the most efficient? It's not like math where you can pick the path with the least amount of writing. The goal is still to accomplish the task in the least amount of steps, but different functions have varying amounts of underlying code.

Simple Example

Let's say you're doing a simple code that removes the word 'foo' and 'bar' from a string. Here are some possible ways to continue...

Possibility 1

$string='I am a foo string. bar';
Possibility 2

$string='I am a foo string. bar';
Possibility 3

$string='I am a foo string. bar';
$kill = array('foo','bar');
$string = str_replace($kill, '', $string);

All of the above examples take an insignificant amount of time to complete, but in real world tasks efficiency is important. For instance, lets say you're removing the most common words from huge files to collect statistics, or you're the cult of scientology and you have 10,000 banned keywords users can't post in your forum.

Testing for Speed with 3 lines

To find the speed we need to start and end a timer, then echo the total time once completed. The following lines accomplish this.

$start=microtime(true); // start timer
$end=microtime(true); // end timer
echo $totaltime=$end-$start; // echo results

Lets apply it to the first example above...


$string='I am a string. bar foo';


echo $totaltime=$end-$start;

It's much more comprehensible to the average person to see the differences in terms of seconds rather than microseconds. Let's say that one example takes 1 millisecond and another takes 5 milliseconds. What's a few milliseconds anyway? If you ever have code that runs for hours on end you'll understand 5 times faster is 5 times faster. Setting up a long loop can help make differences evident.

$string='I am a string. bar foo';
for ($i=0;$i<10000;$i++){


Don't echo anything or add any other irrelevant code between the timers. Doing so will skew the results.


  1. Opening Links: fopen vs fsockopen vs file_get_contents vs Curl
  2. Using double quotes vs single quotes for strings that have tons of variables inside.
  3. loops: foreach vs switch/case vs for vs while/do

Tags: php, speed test, benchmark, scientology, efficiency, php tricks

stumble digg delicious

Blog by Jimmy Ruska
Add me: Youtube, Twitter, Facebook, MySpace


More OMFG-Good Links

See all Posts in the Funny Pictures category.
Download mp3s faster than limewire using google.
I've made 100+ free video tutorials.
See the best of the internet today on one page.