def timer(function): """ A decorator that makes the decorated *function* return its execution time.""" @functools.wraps(function) def wrapper(*args, **kwargs): t1 = time.time() result = function(*args, **kwargs) t2 = time.time() print(" @time '{}': {:.4f} s.".format(str(function), t2-t1)) return result return wrapper class Timer(object): """Use as a context manager: with Timer() as t: """ def __init__(self, verbose=True): self.verbose = verbose def __enter__(self): self.start = time.time() return self def __exit__(self, *args): self.end = time.time() self.secs = self.end - self.start self.msecs = self.secs # millisecs if self.verbose: print("@Timer: {:.5f} s".format(self.msecs))