Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux技術

Python、sed、grep 文字搜尋效率實測比較

GNU awk 的作者曾在 FreeBSD 郵件列表中解釋「GNU grep 為什麼比 BSD grep 快」,其中提到用到了 Boyer-Moore 演算法。名字聽起來就很厲害,於是我好奇:grep 到底有多快?乾脆拿 Python 和 sed 一起來比一比。

測試資料:20 萬行、約 21MB 的文字檔。

Python:一般正則

#!/usr/bin/python3
import re
f = open('/tmp/test.txt')
for line in f:
 match = re.findall('^This.*want', line)
 if match != []:
  print(match)

Python、sed、grep 文字搜尋效率實測比較

Python:預先編譯正則

#!/usr/bin/python3
import re
f = open('/tmp/test.txt')
re_obj = re.compile('^This.*want')
for line in f:
 match = re_obj.findall(line)
 if match != []:
  print(match)

把正則先 compile 起來,速度直接快了一倍。

Python、sed、grep 文字搜尋效率實測比較

sed

Python、sed、grep 文字搜尋效率實測比較

比編譯後的 Python 又快了一個數量級。

grep

Python、sed、grep 文字搜尋效率實測比較

果然,純文字搜尋這件事,grep 才是最專業的選擇。

結論很實用:日常大量日誌比對、字串抽取,優先交給 grep 或 sed;需要複雜邏輯、結構化處理時再請 Python 出場,而且記得把正則先 compile,光是這一步就能省下一半時間。

Copyright © Linux教程網 All Rights Reserved