Contents
时间/日期函数的效率
Jordan Fung <[email protected]> 发件人当地时间 发送时间 17:37 (GMT+08:00)。发送地当前时间:下午5:43。 ✆ 回复 [email protected] 发送至 [email protected] 日期 2011年1月6日 下午5:37 主题 [CPyUG] 时间、日期函数的效率
最近在对一个日志分析模块进行优化,期间发觉python内不同的时间日期函数的效率相差挺大的,例如,如下一个简单的pythoh程序:
通过cProfile进行分析:
>>python -m cProfile aaa.py 500004 function calls in 5.934 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 5.934 5.934 <string>:1(<module>) 1 0.982 0.982 5.933 5.933 aaa.py:1(<module>) 100000 1.118 0.000 1.118 0.000 {built-in method now} 100000 0.413 0.000 0.413 0.000 {built-in method utcnow} 1 0.000 0.000 5.933 5.933 {execfile} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 100000 0.480 0.000 0.480 0.000 {method 'isoformat' of 'datetime.datetime' objects} 100000 2.809 0.000 2.809 0.000 {method 'strftime' of 'datetime.date' objects} 100000 0.131 0.000 0.131 0.000 {time.time}
可以看出:
- (1)time()消耗的时间为utcnow()的1/3,为now()的1/9
- (2)isoformat()消耗的时间为strftime()的1/6
测试环境为debian lenny/Core 2 DUO 2.2G/2G ram
原因
刚才用strace跟踪了一下,发现strftime和now函数会引起stat64系统调用:
stat64("/etc/localtime", {st_mode=S_IFREG|0644, st_size=405, ...}) = 0
上面两个函数处理的是本地时间,需要时区信息,每次都要检查/etc/localtime这个文件,导致系统调研多出了一倍。 time和utcnow都是处理utc时间,所以不需要读取系统的时区。
反馈
创建 by -- ZoomQuiet [2011-01-06 09:47:59]