我在调查线程Why is reading lines from stdin much slower in C++ than Python?时发现了令人惊讶的python行为。在
如果我从那个线程运行简单的python代码
#!/usr/bin/env python
from __future__ import print_function
import time
import sys
count = 0
start_time = time.time()
for line in sys.stdin:
count += 1
delta_sec = time.time() - start_time
if delta_sec >= 0:
lines_per_sec = int(round(count/delta_sec))
print("Read {0:n} lines in {1:.2f} seconds. LPS: {2:n}".format(count, delta_sec, lines_per_sec))
它以11.5MLPS的速度工作,当我把整个脚本分解成单个函数时
^{pr2}$代码速度高达23M LPS。在
为什么这个简单的重构会使我的代码快2倍?在
我用python2.7在ubuntu13.10上运行了我的测试。
观察字节码帮助我回答了这个问题。 第一个脚本的工作部分的字节码是:
第二个脚本对应部分的字节码为:
^{pr2}$我看到这两个代码之间的实际区别是LOAD_NAME vs LOAD洇FAST和STORE_NAME vs STORE_FAST操作码。 文档http://docs.python.org/2.7/library/dis.html#opcode-LOAD_FAST说 LOAD_FAST只使用索引进行查找,而LOAD_NAME lookups按字符串名称变量。 第一种方法的速度是前者的两倍。在
相关问题 更多 >
编程相关推荐