Python 2.7的新IO库比旧版本快多少?
Python 2.7的更新说明提到:
io库有了新版本,重新用C语言编写,以提高性能。
我试着用了一下Python 2.7,但没有感觉到性能有提升:
>>> from timeit import Timer
>>> t = Timer('f = open("E:\\db.txt", "r"); f.read(); f.close()')
>>> t.timeit(10000)
结果是:
- Python 2.6.5 -- 12.879124022745913
- Python 2.7 -- 12.905614540395504
我是不是做错了什么?
1 个回答
4
如果你查看一下 http://docs.python.org/library/io.html,你会发现,在 Python 2.x 版本中,open()
方法并不是默认用来打开文件的。这个功能是在 Python 3.x 版本中才引入的,那个时候 open()
方法开始使用 io.open()
来打开文件。
试试看:
from timeit import Timer
t = Timer('f = io.open("E:\\db.txt", "r"); f.read(); f.close()', 'import io')
t.timeit(10000)