函数计时-函数装饰器

  1. from functools import wraps
  2. import time
  3. def func_timer(function):
  4. '''
  5. 用装饰器实现函数计时
  6. :param function: 需要计时的函数
  7. :return: None
  8. '''
  9. @wraps(function)
  10. def function_timer(*args, **kwargs):
  11. print('[Function: {name} start...]'.format(name = function.__name__))
  12. t0 = time.time()
  13. result = function(*args, **kwargs)
  14. t1 = time.time()
  15. print('[Function: {name} finished, spent time: {time:.2f}s]'.format(name = function.__name__,time = t1 - t0))
  16. return result
  17. return function_timer
  18. @func_timer
  19. def test():
  20. time.sleep(1.5)
  21. if __name__ == '__main__':
  22. test()
  23. '''
  24. [Function: test start...]
  25. [Function: test finished, spent time: 1.50s]
  26. '''

代码片段计时——上下文管理器

  1. from functools import wraps
  2. import time
  3. class Timer(object):
  4. '''
  5. 用上下文管理器计时
  6. '''
  7. def __enter__(self):
  8. self.t0 = time.time()
  9. def __exit__(self, exc_type, exc_val, exc_tb):
  10. print('[time spent: {time:.2f}s]'.format(time = time.time() - self.t0))
  11. if __name__ == '__main__':
  12. with Timer() as t:
  13. print('do something')