这篇文章主要介绍了python如何统计代码运行的时长,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
1. 背景
有时候,需要统计一段代码运行所用的时长,则可以用到下面的代码。
2. 代码示例
#!/usr/bin/env python import datetime import time start_time = datetime.datetime.now() time.sleep(5) end_time = datetime.datetime.now() delta = end_time - start_time delta_gmtime = time.gmtime(delta.total_seconds()) duration_str = time.strftime("%H:%M:%S", delta_gmtime) print "start time:", start_time print "end time:", end_time print "delta_gmtime:", delta_gmtime print "duration:", duration_str
运行效果:
flying-bird@flyingbird:~/examples/python/time_test$ ./time_test.py start time: 2015-06-09 20:11:47.437286 end time: 2015-06-09 20:11:52.440018 delta_gmtime: time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=5, tm_wday=3, tm_yday=1, tm_isdst=0) duration: 00:00:05 flying-bird@flyingbird:~/examples/python/time_test$
3. 进一步优化
在上面的例子中,还是涉及到一些datetime细节。为此,可以进一步封装。如下:
import datetime import time class TimeDuration(object): 'Time duration.' def __init__(self): pass def start(self): self.start_time = datetime.datetime.now() self.end_time = None def stop(self): if self.start_time is None: print "ERROR: start() must be called before stop()." return self.end_time = datetime.datetime.now() def getDurationStr(self): 'String of duration with the format "%H:%M:%S".' if self.start_time is None or self.end_time is None: print "ERROR: start() and stop() must be called first."; return delta = self.end_time - self.start_time delta_gmtime = time.gmtime(delta.total_seconds()) return time.strftime("%H:%M:%S", delta_gmtime)
调用示例:
flying-bird@flyingbird:~/examples/python/time_test$ cat time_test2.py #!/usr/bin/env python import time import time_utils duration = time_utils.TimeDuration() duration.start() time.sleep(5) duration.stop() print duration.getDurationStr() flying-bird@flyingbird:~/examples/python/time_test$ ./time_test2.py 00:00:05 flying-bird@flyingbird:~/examples/python/time_test$
4. 小结
把一些不熟悉的python细节封装起来,以后调用起来就会简化很多。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
版权声明:
本站所有资源均为站长或网友整理自互联网或站长购买自互联网,站长无法分辨资源版权出自何处,所以不承担任何版权以及其他问题带来的法律责任,如有侵权或者其他问题请联系站长删除!站长QQ754403226 谢谢。
- 上一篇: 详解Django定时任务模块设计与实践
- 下一篇: Django Celery异步任务队列的实现