You have a function and you want to see how long it takes to execute.
Compare time in milliseconds before running the function against the time in milliseconds after running the function to see the elapsed time spent in the function itself:
// create a long nonsense string
$long_str = uniqid(php_uname('a'), true);
// start timing from here
$start = microtime(true);
// function to test
$md5 = md5($long_str);
$elapsed = microtime(true) - $start;
echo "That took $elapsed seconds.\n";
To determine how much time a single function takes to execute, you may not need a full benchmarking package.
Instead, you can get the information you need from the microtime() function. Here are three ways to produce the exact same MD5 hash in PHP:
// PHP's basic md5() function
$hashA = md5('optimize this!');
// MD5 by way of the mhash extension
$hashB = bin2hex(mhash(MHASH_MD5, 'optimize this!'));
// MD5 with the hash() function
$hashC = hash('md5', 'optimize this!');
$hashA, $hashB, and $hashC are all 83f0bb25be8de9106700840d66f261cf. However, the third approach is more than twice as fast as PHP’s basic md5() function.
The dark side of optimization with head-to-head tests like these, though, is that you need to figure in how frequently the function is called in your code and how readable and maintainable the alternative is.
For example, in choosing hash functions, if you need your code to run on PHP versions earlier than 5.1.2 (Heavens forbid!), you either have to use md5() all the time or add a check that, based on PHP’s version (and perhaps whether the mhash extension is installed), decides which function to use.
The absolute time difference between md5() and hash() is on the order of a tenth of a millisecond.
If you’re computing thousands or millions of hashes at a time, it makes sense to insert the extra runtime calculations that choose the fastest functions.
But the fraction of a fraction of a breath of time saved in a handful of hash computations isn’t worth the extra complexity.