ITPub博客

首页 > Linux操作系统 > Linux操作系统 > Python Timer Class - Context Manager for Timing Code Blocks

Python Timer Class - Context Manager for Timing Code Blocks

原创 Linux操作系统 作者:jieforest 时间:2012-06-22 07:56:10 0 删除 编辑

CODE:

from timeit import default_timer


class Timer(object):
    def __init__(self, verbose=False):
        self.verbose = verbose
        self.timer = default_timer
        
    def __enter__(self):
        self.start = self.timer()
        return self
        
    def __exit__(self, *args):
        end = self.timer()
        self.elapsed_secs = end - self.start
        self.elapsed = self.elapsed_secs * 1000  # millisecs
        if self.verbose:
            print 'elapsed time: %f ms' % self.elapsedTo use the Timer (context manager object), invoke it using Python's `with` statement. The duration of the context (code inside your `with` block) will be timed. It uses the appropriate timer for your platform, via the `timeit` module.







来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/301743/viewspace-733605/,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2008-04-23

  • 博文量
    443
  • 访问量
    510263