Я обнаружил удивительное поведение Python во время исследования потока. Почему чтение строк из stdin в C ++ намного медленнее, чем в 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, а когда я разлагаю весь скрипт на одну функцию
#!/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)
скорости кода до 23 м LPS.
Почему этот простой рефакторинг делает мой код в 2 раза быстрее?
Я провел свои тесты с python2.7 на Ubuntu 13.10.