python - Python 2.x 中的 BufferedReader 与 Python 3.x

标签 python performance python-3.x bufferedreader

我有一个程序可以在 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。

Here是有问题的代码。参见第 28 行。调用者负责设置 bufstream。我使用了 bufstream = io.open('testfile', 'rb')

为什么 BufferedReader 读取文件中单个字节的速度有如此大的差异,我如何“修复”Python 2.x 的问题?我正在运行 Python 2.6 和 Python 3.1。

最佳答案

为了给您一个更完整的答案,您需要查看您的代码(或者,更好的是,您的代码的可执行摘要)。

然而,可以从您的配置文件输出中收集到部分答案:io.py 表明“Python 2”(为避免疑义,给出实际版本号)正在 Python 中实现 BufferedReader,而_io.BufferedReader 表明“Python3”正在用 C 实现它。

最新消息:Python 2.6 的 io.py 超过 64Kb,并在前面包含以下注释:

# This is a prototype; hopefully eventually some of this will be
# reimplemented in C.

Python 2.7 的 io.py 大约 4Kb,似乎是 _io 模块的薄包装。

如果您需要有关 2.6 解决方案的真正帮助,请展示您的代码。

Python 2.6 的可能解决方法

代替:

test = io.open('test.bmp', 'rb')

这样做:

test = open('test.bmp', 'rb')

一些粗略的计时数据,包括缺失的链接 (Python 2.7):

Windows 7 Pro,32 位,大约 5 Mb 文件,代码内容是:

while 1:
    c = f.read(1)
    if not c: break

2.6: io.open 20.4s, open 5.1s
2.7: io.open  3.3s, open 4.8s # io.open is better
3.1: io.open  3.6s, open 3.6s # effectively same code is used

所以一个更好的故事似乎是这样的:一般来说,除非你有充分的理由,否则不要乱用 io.open您希望 2.7 运行得更快。

关于python - Python 2.x 中的 BufferedReader 与 Python 3.x,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4531147/

相关文章:

python - 如何在 web2py 中生成多对多关系的 FORM?

python - 谷歌应用引擎: Devserver is hideously slow

python - Numba jit 和延迟类型

performance - 加速嵌套 for 循环

c++ - 在不同的 Visual Studio 平台上运行时间不同?

python-3.x - 如何将循环中的字符串附加到单个输出行?

python - 是否可以使用服务主体通过 Azure Python SDK 方法 get_client_from_auth_file 返回 KeyVaultClient?

c# - 如何在不在 WPF 中创建新的 Point 对象的情况下设置 shape.Position?

python - 在 Python 中从数组中删除一些元素

python - 访问列表特定数字元素的列表并使用 python 合并