我在調查線程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.5M LPS運行簡單的Python代碼,當我分解整個腳本到單一功能
#!/usr/bin/env python
from __future__ import print_function
import time
import sys
def test(input):
count = 0
start_time = time.time()
for line in input:
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))
if __name__ == "__main__":
test(sys.stdin)
碼速度可達23M LPS。
爲什麼這個簡單的重構使我的代碼快2倍?
我在Ubuntu 13.10上運行了python2.7的測試。
locals vs globals – SethMMorton
嘗試'input = sys.stdin for line in input:...'在你的第一個腳本中 –
這個方法不會加速第一個腳本 –