函数计时-函数装饰器
from functools import wrapsimport timedef func_timer(function): ''' 用装饰器实现函数计时 :param function: 需要计时的函数 :return: None ''' @wraps(function) def function_timer(*args, **kwargs): print('[Function: {name} start...]'.format(name = function.__name__)) t0 = time.time() result = function(*args, **kwargs) t1 = time.time() print('[Function: {name} finished, spent time: {time:.2f}s]'.format(name = function.__name__,time = t1 - t0)) return result return function_timer@func_timerdef test(): time.sleep(1.5)if __name__ == '__main__': test()'''[Function: test start...][Function: test finished, spent time: 1.50s]'''
代码片段计时——上下文管理器
from functools import wrapsimport timeclass Timer(object): ''' 用上下文管理器计时 ''' def __enter__(self): self.t0 = time.time() def __exit__(self, exc_type, exc_val, exc_tb): print('[time spent: {time:.2f}s]'.format(time = time.time() - self.t0))if __name__ == '__main__': with Timer() as t: print('do something')