Sunday, November 20, 2016

ruby vs bash benchmark (loops comparison).

Bash relies highly on external commands which make it having a lot of overheads; it's the language of the command line, not a proper programming language; it'll work well when most of time is spend by external binaries.

time ruby bench.rb > /dev/null; time bash bench.sh > /dev/null

real    0m0.875s
user    0m0.869s
sys     0m0.007s

real    0m10.336s
user    0m10.111s
sys     0m0.223s

There's no comparison. ruby is magnitudes faster than bash

The scripts --

Bash --

#! /bin/bash
declare -i i
i=0
while test $i -le 999999
do
    echo hello world
    i=i+1
done

Ruby --

#! /bin/ruby
i = 0
while (i <= 999999)
    puts "hello world"
    i = i + 1
end

In the bash binary there's frequent execution of 2 independent binaries -- test and echo which makes it slow.

However, even if you do not use external commands, bash seems to be still slow --

time ./bash_for.sh 

real    0m4.361s
user    0m4.312s
sys     0m0.048s

time ./ruby_for.rb 

real    0m0.289s
user    0m0.090s
sys     0m0.035s

For scripts --
#! /usr/bin/ruby
tst = Array.new
999999.times {
 |k|
 tst[k] = k
}

and
#! /bin/bash
declare -i tst
for i in {0..999999}
do
 tst[$i]=$i
done


No comments:

Post a Comment