脑课堂编程教育

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

Python 1年前
1014 0 0
脑课堂编程培训

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细节封装起来,以后调用起来就会简化很多。

收藏

本文标题:python如何统计代码运行的时长

本文链接:https://naoketang.com/p/xm079l9k7prk

评论区

推荐课程