我正在比较bash
和的性能dash
(sh
Xubuntu 18.04 中的默认值)。
- 我预计
sh
会比bash
- 我预计按位移位比除法运算符更快。
但是,我遇到了不一致的情况:
λ 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'
命令 | 方法] | 分钟] | 最大[秒] | 相对的 |
---|---|---|---|---|
./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 |
以下是我测试过的脚本:
计算div.bash
#!/usr/bin/env bash
for i in {1..1000000}; do
_=$(( i / 1024 ))
done
计算div.sh
i=1
while [ $i -le 1000000 ]; do
_=$(( i / 1024 ))
i=$(( i + 1 ))
done
计算移位.bash
for i in {1..1000000}; do
_=$(( i >> 10 ))
done
计算移位.sh
#!/usr/bin/env sh
i=1
while [ $i -le 1000000 ]; do
_=$(( i >> 10 ))
i=$(( i + 1 ))
done
对于 5000000,这种差异更加明显:
命令 | 方法] | 分钟] | 最大[秒] | 相对的 |
---|---|---|---|---|
./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'
正如您所看到的,对于bash
和dash
,除法运算符比等效的向右按位移位更快。