bash - 非常慢的 bash 循环
问题描述
我做了一件快速的事情,只是将一些命令填充到一个函数中,然后循环一个文件并为每一行运行它。我对这实现的缓慢速度感到惊讶。
关于如何加快使用臭味功能的这个循环的任何建议?
#!/bin/bash
list="lists/test.txt"
smellyfunc() {
alphabet=abcdefghijklmnopqrstuvwxyz
bgam=bcdefghijklmnopqrstuvwxyz
plaintext=THXGAWDITSFRIDAYTODAY
plaintext=$(echo "$plaintext" | tr A-Z a-z | sed s/[^a-z]//g)
step=0
while test -n "$plaintext"
do
key=$1
length=${#key}
char=${plaintext:0:1}
shift=${key:$step:1}
code=$(echo -n $(($(expr index $bgam $char)-$(expr index $bgam $shift))))
step=$(($(($step+1))%$length))
if [[ $code -lt 0 ]]
then
code=$((code+26))
fi
if [[ $code -gt 25 ]]
then
code=$((code-26))
fi
echo -n ${alphabet:$code:1}
plaintext=${plaintext:1}
done
}
while read line; do
key="$line"
result="$(smellyfunc "$key")"
echo "$result" "$key"
done < $list
谢谢!
解决方案
如果我们重写以便您不需要调用任何外部程序,并且您节省了输出的回显,我们可以获得很大的加速:
# function to mimic `expr index`
index() {
local prefix=${1%%$2*}
local i=${#prefix}
if [[ $prefix == $1 ]]; then
# substring $2 not found in $1
i=-1
fi
echo $((i+1))
}
aromaticfunc() {
local alphabet=abcdefghijklmnopqrstuvwxyz
local bgam=bcdefghijklmnopqrstuvwxyz
local step=0
local -l plaintext=THXGAWDITSFRIDAYTODAY
plaintext=${plaintext//[^a-z]/}
local key length char shift code
local result=""
while [[ -n $plaintext ]]; do
key=$1
length=${#key}
char=${plaintext:0:1}
plaintext=${plaintext:1}
shift=${key:$step:1}
code=$(( $(index $bgam $char) - $(index $bgam "$shift") ))
code=$(( (code+26) % 26 ))
step=$(( (step+1) % length ))
result+=${alphabet:$code:1}
done
echo "$result"
}
然后看看我们是否得到相同的结果:
$ s=$( smellyfunc helloworld )
$ a=$( aromaticfunc helloworld )
$ [[ $s == $a ]] && echo OK || echo different
OK
并且,为了解决这个问题,它更快吗?
$ time for i in {1..100}; do result=$(smellyfunc helloworld); done
real 0m7.339s
user 0m5.739s
sys 0m0.967s
$ time for i in {1..100}; do result=$(aromaticfunc helloworld); done
real 0m2.725s
user 0m1.879s
sys 0m0.613s
所以,大约是 3 倍的加速。
推荐阅读
- c# - 如何根据 xamarin.forms 中的条件更改条目的线条颜色
- r - 在 R 中使用 for 循环保存数据帧
- arrays - 将 ORDS 连接到 Angular
- android - 如何在 Firebase 数据库 android 中增加价值
- asp.net-core - 使用 Swashbuckle 和 NSwag 的 WebApi 中的代码生成复杂输入参数
- c# - 违反 PRIMARY KEY 约束无法在对象中插入重复键
- c# - 如何避免视图名称和路径的魔术字符串?
- svg - 在 Inkscape 中打开 EPS 文件会导致奇怪的线条伪影
- unit-testing - 如何在单元测试中以编程方式设置 target_os?
- javascript - 处理与钩子等效的 setState 异步函数时遇到问题