【发布时间】:2011-12-04 21:47:29
【问题描述】:
为了优化我的 bash 脚本,我将文件加载到一个数组中并尝试从那里进行 grep,我注意到内存中的 grep 比文件中的标准 grep 慢得多,即使考虑到事实上,磁盘 I/O 已被排除在外。
1) 好的,所以我有一个包含名称=值对的大文件(大约 3000 行),这是我的“缓存”。我将它从文件加载到一个数组中(足够直截了当)
# load to array
l_i_array_index=1
while read line
do
g_a_cache[$l_i_array_index]=$line
let "l_i_array_index += 1"
done < $g_f_cache
2) 然后我运行一个搜索性能的小基准测试:
time for i in `seq 1 100`
do
for l_i_array_index in `seq 1 ${#g_a_cache[@]}`
do
echo ${g_a_cache[$l_i_array_index]}
done | grep -c $l_s_search_string > /dev/null
done
real 0m14.387s
user 0m13.846s
sys 0m1.781s
3) 相同,但直接来自磁盘文件:
time for i in `seq 1 100`
do
grep -c $l_s_search_string $g_f_cache > /dev/null
done
real 0m0.347s
user 0m0.161s
sys 0m0.136s
所以性能会差 13 到 40 倍,而实际上应该更好。
我的问题是:1)这种奇怪行为的原因是什么2)这在 bash 中是可以解决的,还是我应该硬着头皮最后在 Python 中重做
附:测试是在 Mac (bash v4) 上完成的,在 Cygwin 中,使用普通 grep(速度更快)每次 ONE 搜索的时间超过一秒,而使用数组方法则超过 10 秒。该脚本接近无法使用..
【问题讨论】: