我有一个在 Python 2 和 Python 3 中运行的程序,但速度有很大差异。我知道在 switch 中进行了一些内部更改,但是 io.BufferedReader 的差异非常大。在这两个版本中,我都使用 io.BufferedReader 因为主程序循环一次只需要一个字节的数据。这是脚本的 cProfile 输出的摘录(请参阅cumtime,而不是 tottime):
Python 2:
ncalls tottime percall cumtime percall filename:lineno(function)
36984 0.188 0.000 0.545 0.000 io.py:929(read)
Python 3:
36996 0.063 0.000 0.063 0.000 {method 'read' of '_io.BufferedReader' objects}
当我打印对象时,它们都返回类似的东西,io.BufferedReader
所以我确定它们都在使用 BufferedReader。
这是有问题的代码。见第 28 行。调用者负责设置 bufstream。我用了bufstream = io.open('testfile', 'rb')
为什么 BufferedReader 读取文件中单个字节的速度会有如此大的差异,我该如何“修复”Python 2.x 的问题?我正在运行 Python 2.6 和 Python 3.1。