2

我有一个在 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。

4

2 回答 2

6

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

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

最新消息:Python 2.6io.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 更快。

于 2010-12-25T19:53:10.563 回答
4

使用 2.7 应该可以解决这个问题。请参阅PEP 3116Python 2.7 文档

在 2.6 中,模块 io 的一部分是用 python 编写的,而在 2.7+中,整个模块是用 C 编写的

于 2010-12-25T19:55:30.767 回答