注意 Python 中 strptime 的效率问题
在python的mail-list上早有人提出这个问题,里面提到使用正则表达式解析。
遂动手测试下:
#!/usr/bin/env python
import datetime
import os
import re
import timeit, cProfile
def strptime():
with open('time.txt', 'r') as f:
for line in f:
line = line.rstrip(os.linesep)
dt = datetime.datetime.strptime(line, "%Y-%m-%d %H:%M:%S")
def reg():
rep = re.compile(r'(\d{4})-(\d{2})-(\d{2})\s(\d{2}):(\d{2}):(\d{2})')
with open('time.txt', 'r') as f:
for line in f:
line = line.rstrip(os.linesep)
m = rep.match(line)
dt = datetime.datetime(int(m.group(1)),
int(m.group(2)),
int(m.group(3)),
int(m.group(4)),
int(m.group(5)),
int(m.group(6))
)
if __name__ == '__main__':
t1 = timeit.Timer("reg()","from __main__ import reg")
t2 = timeit.Timer("strptime()", "from __main__ import strptime")
cProfile.run("t1.timeit(3);print")
print""
cProfile.run("t2.timeit(3);print")
在开发机上得到如下结果:
72741 function calls (72698 primitive calls) in 1.119 CPU seconds
219657 function calls (219510 primitive calls) in 3.176 CPU seconds
可见提升还是很大的。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。