令人难以置信的慢速bash循环

时间:2018-06-08 14:10:53

标签: bash performance function while-loop

我做了一件简单的事情,只是将一些命令填入函数并循环遍历文件并为每一行运行它。我对这种速度缓慢感到惊讶。

关于如何加速使用臭味功能的循环的任何建议?

#!/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

谢谢!

1 个答案:

答案 0 :(得分:2)

如果我们重写以便您不需要调用任何外部程序,并且您节省了回显输出,我们可以获得大幅加速:

# 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倍。