import time class Timer: time = __import__("time") def __enter__(self): self.st = time.time() def __exit__(self, exc_type, exc_val, exc_tb): if exc_type is None: print(time.time() - self.st) return False import random with Timer(): a = 0 for i in range(1000000): a += random.randint(0, 1000) print(a)