rally 开源代码中的一个精妙代码执行计时器,贴在这里备忘。
-
# usage
-
with Timer() as timer:
-
# Code to time
-
-
print(timer.duration())
-
class Timer(object):
-
"""Timer based on context manager interface."""
-
-
def __enter__(self):
-
self.error = None
-
self.start = time.time()
-
return self
-
-
def timestamp(self):
-
return self.start
-
-
def finish_timestamp(self):
-
return self.finish
-
-
def __exit__(self, type, value, tb):
-
self.finish = time.time()
-
if type:
-
self.error = (type, value, tb)
-
-
def duration(self, fmt=False):
-
duration = self.finish - self.start
-
if not fmt:
-
return duration
-
if duration > 60:
-
return "%.2f min" % (duration / 60)
-
if duration > 0.1:
-
return "%.2f sec" % duration
-
return "%.2f msec" % (duration * 1000)
zenith
2023-09-03
阅读(216) | 评论(0) | 转发(0) |