Bash ประสิทธิภาพ — เมื่อสคริปต์ช้า



สคริปต์ที่ประมวลผล 100 บรรทัดเสร็จทันที แต่ 100,000 บรรทัดใช้ 5 นาที — เกือบทุกครั้งสาเหตุคือ “เรียก process ใหม่ทุกรอบ loop” บทนี้ว่าด้วยการหาและแก้

ทำไม bash ช้า: fork มีราคา

ทุกครั้งที่เรียกโปรแกรมภายนอก (grep, sed, cut, basename, date, wc) Bash ต้อง fork + exec — สร้าง process ใหม่ โหลดโปรแกรม รัน แล้วเก็บกวาด ใช้เวลาประมาณ 1–5 มิลลิวินาที

ดูไม่เยอะ แต่ใน loop 100,000 รอบ ที่เรียก 3 โปรแกรมต่อรอบ = 300,000 fork = หลายนาที

# ช้ามาก — 3 fork ต่อบรรทัด
while IFS= read -r line; do
    user=$(echo "$line" | cut -d: -f1)
    home=$(echo "$line" | cut -d: -f6)
    shell=$(echo "$line" | awk -F: '{print $7}')
done < /etc/passwd
# เร็ว — 0 fork ต่อบรรทัด (ให้ read แยก field)
while IFS=: read -r user _ _ _ _ home shell _; do
    :
done < /etc/passwd

วัดก่อนแก้

time ./script.sh                        # เวลารวม

# วัดทีละส่วน
TIMEFORMAT='%R วินาที'
time { parse_input; }
time { process_data; }
time { generate_report; }

# นับ fork (Linux)
strace -f -e trace=clone,fork,vfork -c ./script.sh 2>&1 | tail

# หาบรรทัดที่ช้า
PS4='+ $(date "+%s.%N") ${LINENO}: '
bash -x ./script.sh 2> trace.log
# แล้วดู trace.log — ช่วงไหน timestamp กระโดดเยอะ

แทนโปรแกรมภายนอกด้วย builtin

แทนที่จะใช้
basename "$f"${f##*/}
dirname "$f"${f%/*}
echo "$x" | cut -d: -f1${x%%:*}
echo "$x" | sed 's/foo/bar/'${x/foo/bar}
echo "$x" | tr a-z A-Z${x^^} (bash 4+)
echo "$x" | wc -c${#x}
expr $a + $b$(( a + b ))
echo "$x" | grep -q foo[[ $x == *foo* ]]
cat file (แล้วเก็บ)$(<file) หรือ mapfile
head -1 file (ในตัวแปร)read -r first < file
date +%s ใน loopคำนวณจาก $SECONDS
seq 1 100{1..100} หรือ for (( ))
# ช้า
for f in *.jpg; do
    name=$(basename "$f" .jpg)
    ext=$(echo "$f" | rev | cut -d. -f1 | rev)
done

# เร็ว
for f in *.jpg; do
    name=${f%.jpg}
    ext=${f##*.}
done

รวมงานเป็น pipeline เดียว

# ช้า — อ่านไฟล์ 4 รอบ, 4 process
lines=$(wc -l < big.log)
errors=$(grep -c ERROR big.log)
warns=$(grep -c WARN big.log)
uniq_ips=$(awk '{print $1}' big.log | sort -u | wc -l)

# เร็ว — อ่านรอบเดียว ให้ awk ทำทุกอย่าง
read -r lines errors warns uniq_ips < <(
    awk '
        { lines++ }
        /ERROR/ { errors++ }
        /WARN/  { warns++ }
        { ips[$1] = 1 }
        END { print lines, errors, warns, length(ips) }
    ' big.log
)

awk (หรือ Python) อ่านไฟล์รอบเดียวทำทุกอย่าง — เร็วกว่าหลาย pipe มาก

อย่าเรียก process ใน loop เพื่อสะสมค่า

# ช้า — เรียก bc ทุกรอบ
total=0
while read -r amount; do
    total=$(echo "$total + $amount" | bc)
done < amounts.txt

# เร็ว — ให้ awk รวมทั้งหมด
total=$(awk '{ s += $1 } END { print s }' amounts.txt)

# ถ้าจำเป็นต้องอยู่ใน bash และเป็นจำนวนเต็ม
total=0
while read -r amount; do
    (( total += amount ))
done < amounts.txt

ทำงานขนาน

CPU มีหลาย core — งานที่เป็นอิสระต่อกันรันพร้อมกันได้ (บทที่ 26, 28)

# ช้า — ทีละไฟล์
for img in *.png; do
    convert "$img" -resize 50% "thumb/$img"
done

# เร็ว — xargs -P รันพร้อมกัน N งาน
printf '%s\n' *.png | xargs -P "$(nproc)" -I{} convert {} -resize 50% thumb/{}

# หรือ GNU parallel
parallel -j "$(nproc)" convert {} -resize 50% thumb/{} ::: *.png

ระวัง: งานที่ติด I/O (ดิสก์/network) การเพิ่ม parallelism อาจไม่ช่วย หรือแย่ลง — วัดจริง

mapfile แทนการวน $(cmd)

# ช้า — command substitution + word splitting
for line in $(cat config.txt); do ...; done

# เร็ว + ถูกต้อง
mapfile -t lines < config.txt
for line in "${lines[@]}"; do ...; done

case แทน chain ของ grep / if

# ช้า — fork grep ทุกครั้ง
if echo "$file" | grep -q '\.txt$'; then type=text
elif echo "$file" | grep -q '\.jpg$'; then type=image
fi

# เร็ว — case ใช้ glob ในตัว ไม่ fork
case $file in
    *.txt) type=text ;;
    *.jpg | *.png) type=image ;;
    *) type=unknown ;;
esac

เมื่อไหร่ควรเลิกใช้ bash

Bash ถึงขีดจำกัด — ย้ายไป awk / Python / Go เมื่อ

  • loop ประมวลผลข้อมูล > ~10,000 รอบ และแต่ละรอบมีตรรกะ — awk หรือ Python เร็วกว่า 10–100 เท่า
  • ต้องการโครงสร้างข้อมูล — nested dict, list of objects → Python
  • คำนวณเลขจริงจัง / ทศนิยม / สถิติ → Python (numpy), awk, R
  • parse รูปแบบซับซ้อน — CSV จริง, JSON ลึก, XML → เครื่องมือเฉพาะ
  • โค้ดเกิน ~200 บรรทัดและตรรกะเยอะ — อ่านและเทสยาก
  • ต้องการ unit test ครอบคลุม — bats ทำได้ แต่ Python/Go เป็นธรรมชาติกว่า

ไม่ใช่ “bash แย่” — แต่ bash เก่งเรื่อง glue (เรียกโปรแกรม ต่อท่อ จัดคิว) พองานเป็น “ประมวลผลข้อมูล” ล้วน ๆ เครื่องมืออื่นเหมาะกว่า

# แทนที่จะเขียน text processing 80 บรรทัดใน bash
python3 <<'EOF'
import sys, json, collections
counts = collections.Counter()
for line in open("access.log"):
    counts[line.split()[0]] += 1
for ip, n in counts.most_common(10):
    print(f"{n:6d} {ip}")
EOF

เรื่องที่คนมักพลาด

  • $(echo "$x" | cmd) ใน loop — แต่ละรอบ fork 2 process ใช้ parameter expansion
  • อ่านไฟล์เดียวหลายรอบ — wc, grep, grep, awk แยกกัน ให้ awk ทำรอบเดียว
  • total=$(echo "$total+$x" | bc) ใน loop — ให้ awk sum ทั้งไฟล์ทีเดียว
  • ทำทีละไฟล์ทั้งที่ขนานได้ — xargs -P $(nproc) หรือ parallel
  • optimize โดยไม่วัด — time ก่อน หาว่าช้าตรงไหนจริง
  • ฝืนเขียน text processing ใหญ่ ๆ ใน bash — 20 บรรทัด awk/Python แทน 100 บรรทัด bash
  • เพิ่ม parallel กับงาน I/O-bound — ดิสก์เดียวอ่านขนานไม่ได้เร็วขึ้น วัดจริง

สรุป

  • Bash ช้าเพราะ fork process มีราคา — ปัญหาโผล่เมื่อ loop ใหญ่ + เรียกโปรแกรมทุกรอบ
  • วัดก่อน: time, TIMEFORMAT, PS4 มี timestamp + bash -x
  • แทน external ด้วย builtin: ${f##*/}, ${x%%:*}, ${x^^}, $(( )), [[ == * ]], case
  • ให้ read -r a b c แยก field แทน cut/awk ต่อรอบ
  • รวมงานให้ awk อ่านไฟล์รอบเดียว แทนหลาย pipe/grep
  • ขนาน: xargs -P $(nproc) หรือ parallel (งาน CPU-bound ที่อิสระต่อกัน)
  • เลิกใช้ bash เมื่อ: loop > 10k รอบมีตรรกะ, ต้องการโครงสร้างข้อมูล, คณิตศาสตร์จริง, โค้ด > 200 บรรทัด → awk / Python

จบเฟส 5 — บทถัดไปเข้าเฟส 6 เรื่องใช้งานจริง เริ่มจากการรันสคริปต์อัตโนมัติด้วย cron และ systemd timer