首先来看一个小程序,这个是计量所花费时间的程序,以下是以往的解决示例
from functools import wraps, partialfrom time import timedef timing(func=none, frequencies=1): if func is none: # print(+none) return partial(timing, frequencies=frequencies) # else: # print(-none) @wraps(func) def _wrapper(*args, **kwargs): start_time = time() for t in range(frequencies): result = func(*args, **kwargs) end_time = time() print('运行花费时间:{:.6f}s。'.format(end_time-start_time)) return result return _wrapper@timingdef run(): l = [] for i in range(5000000): l.extend([i]) return len(l)
运行如下:
in [4]: run()运行花费时间:2.383398s。out[4]: 5000000
(喜欢刨根问底的可以去掉注释,并思考预计会有什么样的输出)。
今天无意间看到了python的上下文管理器(context manager),发现也非常不错,其实这跟with语句是息息相关的,竟然以前一直未在意。
from time import timedef run2(): l = [] for i in range(5000000): l.extend([i]) return len(l)class elapsedtime(): def __enter__(self): self.start_time = time() return self def __exit__(self, exception_type, exception_value, traceback): self.end_time = time() print('运行花费时间:{:.6f}s。'.format(self.end_time - self.start_time))with elapsedtime(): run2()
总结
初略看了一点官方文档,上下文管理还是有点多内容的。python发展到现在,其实不简单了。说简单,只是你自己不够与时俱进,掌握的都是老式三板斧而已。所以,知识需要不断更新,才能弥补自己的盲点,以上就是本文的全部内容,希望能大家的学习或者工作带来一定的帮助。