views:

112

answers:

3

I've REALLY been wanting to test speeds of regex etc. and on php.net it has this example:

$time_start = microtime(true);

// Sleep for a while
usleep(100); // Or anything for that matter..

$time_end = microtime(true);
$time = $time_end - $time_start;

echo "Did nothing in $time seconds\n";

EDIT: What I meant was to play a large loop of functions in place of usleep(). It always shows a very random number that is always under 1. It shows nothing worth a benchmark!

+1  A: 

The usleep function need time in microsecond, you are specifying very low value, try increasing that:

usleep(2000000); // wait for two seconds

usleep function is also known to be tricky on Windows systems.

Or you can simply use the sleep function with seconds to be specified as its parameter eg:

sleep(10); // wait for 10 seconds
Sarfraz
+1  A: 

Cannot reproduce, and no one has a faster computer than me. 16 threads of execution, eight cores, i7 architecture. Your PHP build or OS must be suboptimal. This is running your code exactly.

`--> php tmp.php
Did nothing in 0.00011587142944336 seconds
.-(/tmp)---------------------------------------------------(pestilence@pandemic)-

This is with usleep(1000000)... (1 second)

`--> php tmp.php
Did nothing in 1.0000479221344 seconds
.-(/tmp)---------------------------------------------------(pestilence@pandemic)-

FYI, I was using PHP 5.3.0, not that it makes any difference (in this case) past 5.0.

Is your code taking less than a second to execute? If so, that'd explain your benchmarks. When I profile something for an article, I run my routine 10,000's of times... sometimes millions. Computers are fast these days.

As far as the "random" part goes, this is why I take several samples of large iterations and average them together. It doesn't hurt to throw the standard deviation in there too. Also, remember not to stream MP3s or play video while testing. :p

Pestilence
+1  A: 

Timers are like that. Wrap a loop around the function. Run it 10^6 times if you want to measure microseconds, 10^3 times if you want milliseconds. Don't expect to get more than 2 decimal digits of precision.

Mike Dunlavey