import time class M_TimeCounter(): def __init__(self,prefix=None): self.prefix=prefix+' ' if prefix else ' ' def __enter__(self): self.start=time.time() def __exit__(self, exc_type, exc_val, exc_tb): print('%stime: %.4f sec' %(self.prefix,time.time()-self.start)) def run(x): for _ in range(x): y=100/10 with M_TimeCounter(): run(1000000)