您好,登錄后才能下訂單哦!
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細節封裝起來,以后調用起來就會簡化很多。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。