Quick benchmark from the command line

Viewed 4458

I'd like to benchmark a PHP script, but this would equally apply to anything that can be run from the command line.

Using bash is there a simple way to benchmark a script, i.e. run a command multiple times and time how long it takes?

4 Answers

To add to Xiè Jìléi answer, if one does not want to calculate average by hand:

: > benchmark.tmp
for i in {1..10} ; do \
    /usr/bin/time --output benchmark.tmp --append --format "%e" -- custom-cmd-for-benchmark ; \
done
awk '{ total += $1; count++ } END { print total/count }' benchmark.tmp

or oneliner:

RETRIES=10 ; CMD="custom-cmd-for-benchmark"; /usr/bin/time --output benchmark.tmp --format "%e" -- bash -c "for i in {1..${RETRIES}} ; do ${CMD} ; done" ; awk "{ print \$1/${RETRIES} }" benchmark.tmp

NOTE: {1..10} defines number of retires

NOTE2: this is not using bash built-in time for better control over output stream (in case custom-cmd-for-benchmark outputs something)!

WARNING: this overrides benchmark.tmp file!

Other ideas (for better precision, but drop std output, which may bias benchmark, as writing to /dev/null may be faster than to terminal):

# This using bash built-in + TIMEFORMAT variable
( export TIMEFORMAT='%3R' ; time for i in {1..10} ; do custom-cmd-for-benchmark >/dev/null ; done ) 2>&1 | awk '{ print $1/10 }'

# This using `date` tool
( date +'%s.%N' | tr -d "\n"; for i in {1..10} ; do custom-cmd-for-benchmark >/dev/null ; done ; date +' %s.%N' ) | awk '{ printf "%.4f",($2 - $1)/10 }'

if you're just looking for phpBogoMips,

$ time php -r 'for($outer=0;$outer<10;++$outer){$t=microtime(true);for($i=0;$i<10000000;++$i){}$t=microtime(true)-$t;$phpBogoMips=10/$t;echo "phpBogoMips: ",$phpBogoMips,PHP_EOL;}'
phpBogoMips: 66.581855298938
phpBogoMips: 74.053284839068
phpBogoMips: 75.23266805498
phpBogoMips: 113.19650341535
phpBogoMips: 84.938811631359
phpBogoMips: 102.55999960876
phpBogoMips: 103.25660631902
phpBogoMips: 84.562239668388
phpBogoMips: 77.247435401588
phpBogoMips: 78.314767444032

real    0m1.307s
user    0m1.124s
sys     0m0.078s
  • it counts how many times per second PHP can count to 1 million..
  • the wide variation here can probably attributed to me running it on a laptop-on-battery? is because i ran it on a laptop on battery. screenshot on dedicated servers with more consistent results (the left-most is the laptop, and it shows): https://i.imgur.com/O8wqojf.png
  • someone should doube-check my math here, i'm not 100% certain i got it right. - someone did! the math seems about right.
Related