python이랑 c++에서 stdin
으로부터 한 줄씩 입력받는 프로그램을 돌렸는데
C++이 훨씬 느려요.
보통은 python이 훨씬 느리지 않나요?
제가 코드를 이상하게 짜서 그런가요? 뭐가 잘못된지 모르겠어요
OS X(10.6.8)랑 리눅스(RHEL 6.2)에서 실행했습니다
소스코드1 - c++
C++ code:
#include <iostream>
#include <time.h>
using namespace std;
int main() {
string input_line;
long line_count = 0;
time_t start = time(NULL);
int sec;
int lps;
while (cin) {
getline(cin, input_line);
if (!cin.eof())
line_count++;
};
sec = (int) time(NULL) - start;
cerr << "Read " << line_count << " lines in " << sec << " seconds." ;
if (sec > 0) {
lps = line_count / sec;
cerr << " LPS: " << lps << endl;
} else
cerr << endl;
return 0;
}
//g++ -O3 -o readline_test_cpp foo.cpp로 컴파일
소스코드2 - python
#!/usr/bin/env python
import time
import sys
count = 0
start = time.time()
for line in sys.stdin:
count += 1
delta_sec = int(time.time() - start_time)
if delta_sec >= 0:
lines_per_sec = int(round(count/delta_sec))
print("Read {0} lines in {1} seconds. LPS: {2}".format(count, delta_sec,
lines_per_sec))
결과 :
$ cat test_lines | ./readline_test_cpp
Read 5570000 lines in 9 seconds. LPS: 618889
$cat test_lines | ./readline_test.py
Read 5570000 lines in 1 seconds. LPS: 5570000