编译代码性能比非编译代码性能好,简单测试一下。
- #!/usr/bin/env python
- import re
- from time import ctime
- def run():
- pattern='case'
- rere_obj=re.compile(pattern)
- infile=open('/etc/rc.subr','r')
- match_count=0
- lines=0
- for line in infile:
- match=re_obj.search(line)
- if match:
- match_count+=1
- lines+=1
- return (lines,match_count)
- if __name__=='__main__':
- print('starting at:',ctime())
- lines,match_count=run()
- print "LINES:",lines
- print "MATCHS:",match_count
- print('ending at:',ctime())
运行一下
- # python re_test.py
- ('starting at:', 'Sun Mar 11 15:34:03 2012')
- LINES: 1693
- MATCHS: 27
- ('ending at:', 'Sun Mar 11 15:34:03 2012')
打开的测试文件不够大,1秒内完成了。
使用unix time命令看看
# time python re_test.py
('starting at:', 'Sun Mar 11 15:35:10 2012') LINES: 1693 MATCHS: 27 ('ending at:', 'Sun Mar 11 15:35:10 2012') 0.020u 0.048s 0:00.06 100.0% 1740+1322k 0+0io 0pf+0w也可以使用IPython的timeit工具测试
import re_test
timeit -n 1 re_test.run()
-n后面接执行代码的次数