Anrs Hu

你所知的一切…

unpack 的三种实现

with 2 comments

解析文件或者网络数据时,基本的操作就是 unpack 流内容,下面演示了三种不同的 unpack 手法,分别使用了 re, struct.unpack 和 list slice,最后是三种手法的性能比较。

代码:

  1. #!/usr/bin/env python
  2. def split_by_unpack(txt):
  3.     import struct
  4.     baseformat = ‘5s 3x 8s 8s’
  5.     format = ‘%s %ds’ % (baseformat, len(txt)struct.calcsize(baseformat))
  6.     return struct.unpack(format, txt)
  7.  
  8. def _split_by_re():
  9.     import re
  10.     regex = re.compile(r‘(.{5})(?:.{3})(.{8})(.{8})(.*)’, re.I)
  11.     def __split_by_re(txt):
  12.         r = regex.match(txt)
  13.         return (r.group(1), r.group(2), r.group(3), r.group(4))
  14.     return __split_by_re
  15. split_by_re = _split_by_re()
  16.  
  17. def split_by_slice(txt):
  18.     cuts = [5, 8, 16, 24]
  19.     pieces = [txt[i:j] for i, j in zip([0] + cuts, cuts + [None])]
  20.     return (pieces[0], pieces[2], pieces[3], pieces[4])
  21.  
  22.  
  23. if __name__ == ‘__main__’:
  24.     txt = ‘12345###abcdefghABCDEFGH###’
  25.     for i in xrange(1000000):
  26.         split_by_slice(txt)
  27.         split_by_unpack(txt)
  28.         split_by_re(txt)
  29.  

上面代码演示了将文本 unpack 为长度分别是 5, 3(忽略), 8, 8, k 的子串,下面是对三个函数进行百万次调用后的性能分析:

screenshot_052

其实三种手法还是有一些差异的,struct.unpack 是基于 bytes 来拆分,而 re 和 list slice 是基于字符拆分的,所以在非 ASCII 的情况下要特别注意。

Written by admin

September 8th, 2009 at 9:13 am

Posted in Coding

Tagged with ,

2 Responses to 'unpack 的三种实现'

Subscribe to comments with RSS or TrackBack to 'unpack 的三种实现'.

  1. 你最近博瘾有点大哦

    hkbarton

    8 Sep 09 at 11:33 am

  2. 最近在看”PyCookbook”,里面有很多能带来灵感的好东东,值得分享…

    admin

    9 Sep 09 at 1:01 am

Leave a Reply