服务器之家:专注于服务器技术及软件下载分享
分类导航

Linux|Centos|Ubuntu|系统进程|Fedora|注册表|Bios|Solaris|Windows7|Windows10|Windows11|windows server|

服务器之家 - 服务器系统 - Linux - Python与sed,grep文本查找效率对比小测

Python与sed,grep文本查找效率对比小测

2019-11-27 19:27脚本之家 Linux

这篇文章主要针对python,sed与grep查找文本的效率做一个实验,方便以后选择使用什么工具,需要的朋友可以参考下

Gnu awk作者在FreeBSD邮件列表中回答”GNU grep为什么比BSD grep要快“,提到了用到了Boyer-Moore算法,虽然不知道是什么,但感觉很厉害的样子~我猜想grep有多快呢? 

所以想比较下下python,sed与grep: 

测试文本:20w行,21M大 

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文本查找效率对比小测

试下编译的正则试试: 
 

复制代码

代码如下:


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



结果快了1倍:

Python与sed,grep文本查找效率对比小测


试试sed:

Python与sed,grep文本查找效率对比小测

快了1个数量级! 

最后试试grep:

Python与sed,grep文本查找效率对比小测


果然grep是查找最专业的!

延伸 · 阅读

精彩推荐