Cha*_*ath 17 python performance file-io
我知道有很多关于在python中读取文件的文章和问题.但我仍然想知道是什么让python有多种方法来完成同样的任务.我想知道的是,使用这两种方法对性能有何影响?
Ana*_*mar 36
使用with语句不是为了提高性能,我认为使用语句不会产生任何性能上的提升或损失with,只要您执行与using with语句自动执行相同的清理活动.
当您使用with带有open函数的语句时,您不需要在结尾处关闭文件,因为with它会自动为您关闭它.
此外,with声明不仅适用于打开文件,还与上下文管理器结合使用.基本上,如果您有一个对象要确保在完成它之后清除它或发生某种错误,您可以将其定义为上下文管理器,并且with语句将在进入和退出时调用它__enter__()和__exit__()方法与块.根据PEP 0343 -
这个PEP
with为Python语言添加了一个新的语句,以便能够分解try/finally语句的标准用法.在这个PEP,上下文管理器提供
__enter__()和__exit__()方法,这些方法与声明进入和退出的身体调用.
此外,使用with和不使用它的性能测试-
In [14]: def foo():
....: f = open('a.txt','r')
....: for l in f:
....: pass
....: f.close()
....:
In [15]: def foo1():
....: with open('a.txt','r') as f:
....: for l in f:
....: pass
....:
In [17]: %timeit foo()
The slowest run took 41.91 times longer than the fastest. This could mean that an intermediate result is being cached
10000 loops, best of 3: 186 µs per loop
In [18]: %timeit foo1()
The slowest run took 206.14 times longer than the fastest. This could mean that an intermediate result is being cached
10000 loops, best of 3: 179 µs per loop
In [19]: %timeit foo()
The slowest run took 202.51 times longer than the fastest. This could mean that an intermediate result is being cached
10000 loops, best of 3: 180 µs per loop
In [20]: %timeit foo1()
10000 loops, best of 3: 193 µs per loop
In [21]: %timeit foo1()
10000 loops, best of 3: 194 µs per loop
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
28105 次 |
| 最近记录: |