スレッドWhy is reading lines from stdin much slower in C++ than Python?を調べているうちに、私は驚くべきpythonの動作を発見しました。メッシュのpythonコードが分解されたものより遅いのはなぜですか?
は、私はそれがスピード11.5M LPSで動作し、そのスレッド
#!/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))
から、簡単な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でテストを実行しました。
ローカル対グローバル – SethMMorton
最初のスクリプトで 'input = sys.stdin for line in input:...'を試してください –
このメソッドは最初のスクリプトを高速化しません –