Python Timer Class - Context Manager for Timing Code Blocks

jieforest發表於2012-06-22

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/,如需轉載,請註明出處,否則將追究法律責任。

相關文章