python如何统计代码运行的时长

时间:2021-05-23

1. 背景

有时候,需要统计一段代码运行所用的时长,则可以用到下面的代码。

2. 代码示例

#!/usr/bin/env python import datetimeimport time start_time = datetime.datetime.now()time.sleep(5)end_time = datetime.datetime.now()delta = end_time - start_timedelta_gmtime = time.gmtime(delta.total_seconds())duration_str = time.strftime("%H:%M:%S", delta_gmtime) print "start time:", start_timeprint "end time:", end_timeprint "delta_gmtime:", delta_gmtimeprint "duration:", duration_str

运行效果:

flying-bird@flyingbird:~/examples/python/time_test$ ./time_test.py start time: 2015-06-09 20:11:47.437286end time: 2015-06-09 20:11:52.440018delta_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:05flying-bird@flyingbird:~/examples/python/time_test$

3. 进一步优化

在上面的例子中,还是涉及到一些datetime细节。为此,可以进一步封装。如下:

import datetimeimport 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 timeimport 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.py00:00:05flying-bird@flyingbird:~/examples/python/time_test$

4. 小结

把一些不熟悉的python细节封装起来,以后调用起来就会简化很多。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章