文章写的不是很严谨,欢迎来喷,另外该文后续有更新的,请到原文地址查看更新.
正题:
我们经常会有统计python程序里面统计某个逻辑消耗时间的需求,我想大家最常用的方法应该是下面的这种。 如果你的计时逻辑太多,需要在统计的前后加入开始时间,结束时间记录, 显得很是麻烦 。
start_time = time.time()
do()
end_time = time.time()
logger.info("hbase action timecost %s"%end_time-start_time)
除了上面土方法,python提供了一个timeit的模块. 但本人不喜欢timeit Timer的方式,因为不灵活.
#blog: xiaorui.cc
import timeit
t2 = timeit.Timer('x=range(1000)')
#显示所花费的时间
t2.timeit()
10.620039563513103
#执行命令
t1 = timeit.Timer('sum(x)', 'x = (i for i in range(1000))')
#显示时间
t1.timeit()
0.1881566039438201
我就是为了省事,所以搞了一个专门计时的小模块,兼容了各种的时间格式,另外可以方便的使用装饰器,with关键词的方式来统计消耗时间。 不管是with,装饰器大家可能都会,但有时你的场景只是写个临时测试脚本,那你还专门写个with (enter exit) , decorator (func()) ? 这模块主要是为了我自己偷懒做的.
抽时间把代码推到github和pypi了, 其实代码的功能和结构都简单,没什么好说的.
github地址, https://github.com/rfyiamcool/TimeCost
安装方法:
pip install TimeCost
下面说下他的用法:
使用with关键词和装饰器来统计时间
#blog : xiaorui.cc
from timecost import TimeCost
@TimeCost('s',0)
def test():
print 123
if __name__ == "__main__":
with TimeCost('s',0) as t:
resutl = sum(range(100))
print t.total
print test()
另外装饰器统计时间的方法支持传递logger对象的.
#blog: xiaorui.cc
import logging
def init_logger(logfile):
logger = logging.getLogger()
logger.setLevel(logging.INFO)
fmt = '%(asctime)s - %(process)s - %(levelname)s: - %(message)s'
formatter = logging.Formatter(fmt)
handler = logging.FileHandler(logfile)
handler.setFormatter(formatter)
logger.addHandler(handler)
return logger
logger = init_logger('debug')
@TimeCost('s',0,logger)
def test():
pass
对于python耗时统计就说到这里了,其实本来就没啥说的… 啰嗦一句, 推荐大家使用装饰器的方式统计花费时间,这样能最少的改变代码结构.
