编译代码性能比非编译代码性能好,简单测试一下。

 
  
  1. #!/usr/bin/env python 
  2. import re 
  3. from time import ctime 
  4. def run(): 
  5.         pattern='case' 
  6.         rere_obj=re.compile(pattern) 
  7.         infile=open('/etc/rc.subr','r') 
  8.         match_count=0 
  9.         lines=0 
  10.         for line in infile: 
  11.                 match=re_obj.search(line) 
  12.                 if match: 
  13.                         match_count+=1 
  14.                 lines+=1 
  15.         return (lines,match_count) 
  16. if __name__=='__main__': 
  17.         print('starting at:',ctime()) 
  18.         lines,match_count=run() 
  19.         print "LINES:",lines 
  20.         print "MATCHS:",match_count 
  21.         print('ending at:',ctime()) 

运行一下

 
  
  1. # python re_test.py 
  2. ('starting at:', 'Sun Mar 11 15:34:03 2012') 
  3. LINES: 1693 
  4. MATCHS: 27 
  5. ('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后面接执行代码的次数