使用with语句,计算python执行时间

import time

class Timer:    
    def __enter__(self):
        self.start = time.clock()
        return self

    def __exit__(self, *args):
        self.end = time.clock()
        self.interval = self.end - self.start

with Timer() as t:
    i = 1+1
    time.sleep(1)
    i = i + 2
print('took %.03f sec.' % t.interval)

你可能感兴趣的:(使用with语句,计算python执行时间)