首页 > 解决方案 > 非常慢的 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

谢谢!

标签: bashperformancefunctionwhile-loop

解决方案


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

# 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 倍的加速。


推荐阅读