精妙代码计时器

320阅读 0评论2023-09-03 zenith518
分类:Python/Ruby

rally 开源代码中的一个精妙代码执行计时器,贴在这里备忘。

点击(此处)折叠或打开

  1. # usage
  2. with Timer() as timer:
  3.    # Code to time

  4. print(timer.duration())

点击(此处)折叠或打开

  1. class Timer(object):
  2.     """Timer based on context manager interface."""

  3.     def __enter__(self):
  4.         self.error = None
  5.         self.start = time.time()
  6.         return self

  7.     def timestamp(self):
  8.         return self.start

  9.     def finish_timestamp(self):
  10.         return self.finish

  11.     def __exit__(self, type, value, tb):
  12.         self.finish = time.time()
  13.         if type:
  14.             self.error = (type, value, tb)

  15.     def duration(self, fmt=False):
  16.         duration = self.finish - self.start
  17.         if not fmt:
  18.             return duration
  19.         if duration > 60:
  20.             return "%.2f min" % (duration / 60)
  21.         if duration > 0.1:
  22.             return "%.2f sec" % duration
  23.         return "%.2f msec" % (duration * 1000)

zenith
2023-09-03


上一篇:为vicuna增加用户认证
下一篇:一些特殊符号的Unicode码