Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1065842
  • 博文数量: 239
  • 博客积分: 10
  • 博客等级: 民兵
  • 技术积分: 3618
  • 用 户 组: 普通用户
  • 注册时间: 2012-11-12 13:17
文章分类

全部博文(239)

文章存档

2021年(1)

2016年(1)

2015年(30)

2014年(91)

2013年(116)

分类: LINUX

2014-02-22 23:46:54

此脚本找到large_re_file.txt的行数以及pDq的行数。

点击(此处)折叠或打开

  1. [root@oracle11g test]# cat re_loop_nocompile.py
  2. #!/usr/bin/env python

  3. import re

  4. def run_re():
  5.     pattern = 'pDq'
  6.     
  7.     infile = open('large_re_file.txt', 'r');
  8.     match_count = 0
  9.     lines = 0
  10.     for line in infile:
  11.         match = re.search(pattern, line)
  12.         if match:
  13.             match_count += 1
  14.         lines += 1
  15.     return (lines, match_count)

  16. if __name__ == "__main__":
  17.     lines, match_count = run_re()
  18.     print 'LINES::',lines
  19.     print 'MATCHES::',match_count

large_re_file.txt 里面的内容如下:
[root@oracle11g test]# cat large_re_file.txt 
pDq
pattern

执行脚本如下:
[root@oracle11g test]# ./re_loop_nocompile.py 
LINES:: 2
MATCHES:: 1

ipython运行loop的调用时间
[root@oracle11g test]# ipython
/usr/lib/python2.6/site-packages/IPython/Magic.py:38: DeprecationWarning: the sets module is deprecated
  from sets import Set
Python 2.6.6 (r266:84292, May  1 2012, 13:52:17) 
Type "copyright", "credits" or "license" for more information.


IPython 0.9.1 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object'. ?object also works, ?? prints more.


In [1]: import re_loop_nocompile


In [2]: timeit -n 5 re_loop_nocompile.run_re()
5 loops, best of 3: 22.6 ?s per loop
调用函数5次,每次22.6us

使用unix/linux脚本测试时间
[root@oracle11g test]# time python re_loop_nocompile.py
LINES:: 2
MATCHES:: 1


real 0m0.030s
user 0m0.022s
sys 0m0.009s


阅读(3254) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~