I'm comparing performance of bash
and dash
(default sh
in Xubuntu 18.04).
- I expect
sh
to be faster thanbash
- I expect bitwise shift to be faster than division operator.
However, I'm getting inconsistencies:
λ hyperfine --export-markdown a.md -w 3 ./*
Benchmark #1: ./calc-div.bash
Time (mean ± σ): 2.550 s ± 0.033 s [User: 2.482 s, System: 0.068 s]
Range (min … max): 2.497 s … 2.595 s 10 runs
Benchmark #2: ./calc-div.sh
Time (mean ± σ): 2.063 s ± 0.016 s [User: 2.063 s, System: 0.000 s]
Range (min … max): 2.043 s … 2.100 s 10 runs
Benchmark #3: ./calc-shift.bash
Time (mean ± σ): 3.312 s ± 0.034 s [User: 3.255 s, System: 0.057 s]
Range (min … max): 3.274 s … 3.385 s 10 runs
Benchmark #4: ./calc-shift.sh
Time (mean ± σ): 2.087 s ± 0.046 s [User: 2.086 s, System: 0.001 s]
Range (min … max): 2.058 s … 2.211 s 10 runs
Summary
'./calc-div.sh' ran
1.01 ± 0.02 times faster than './calc-shift.sh'
1.24 ± 0.02 times faster than './calc-div.bash'
1.61 ± 0.02 times faster than './calc-shift.bash'
Command | Mean [s] | Min [s] | Max [s] | Relative |
---|---|---|---|---|
./calc-div.bash |
2.550 ± 0.033 | 2.497 | 2.595 | 1.24 ± 0.02 |
./calc-div.sh |
2.063 ± 0.016 | 2.043 | 2.100 | 1.00 |
./calc-shift.bash |
3.312 ± 0.034 | 3.274 | 3.385 | 1.61 ± 0.02 |
./calc-shift.sh |
2.087 ± 0.046 | 2.058 | 2.211 | 1.01 ± 0.02 |
Here are the scripts I tested:
calc-div.bash
#!/usr/bin/env bash
for i in {1..1000000}; do
_=$(( i / 1024 ))
done
calc-div.sh
i=1
while [ $i -le 1000000 ]; do
_=$(( i / 1024 ))
i=$(( i + 1 ))
done
calc-shift.bash
for i in {1..1000000}; do
_=$(( i >> 10 ))
done
calc-shift.sh
#!/usr/bin/env sh
i=1
while [ $i -le 1000000 ]; do
_=$(( i >> 10 ))
i=$(( i + 1 ))
done
This difference is more visible for 5000000:
Command | Mean [s] | Min [s] | Max [s] | Relative |
---|---|---|---|---|
./calc-div.bash |
13.333 ± 0.202 | 12.870 | 13.584 | 1.23 ± 0.02 |
./calc-div.sh |
10.830 ± 0.119 | 10.750 | 11.150 | 1.00 |
./calc-shift.bash |
17.361 ± 0.357 | 16.995 | 18.283 | 1.60 ± 0.04 |
./calc-shift.sh |
11.226 ± 0.351 | 10.834 | 11.958 | 1.04 ± 0.03 |
Summary
'./calc-div.sh' ran
1.04 ± 0.03 times faster than './calc-shift.sh'
1.23 ± 0.02 times faster than './calc-div.bash'
1.60 ± 0.04 times faster than './calc-shift.bash'
As you can see, for both bash
and dash
, division operator is faster than equivalent bitwise-shift to the right.
bash
in expanding "{1..1000000}
". Use the same "do it a million times" code in both shells. "{1..1000000}
" expands into "1 2 3 4 5 6 ... 999998 999999 1000000
" which is a large string.