C++에서 stdin으로 라인 입력 받는 것이 왜 Python 보다 느린가요..

LONGNEW·2021년 1월 13일
0

StackOverFlaw

목록 보기
16/16

https://stackoverflow.com/questions/9371238/why-is-reading-lines-from-stdin-much-slower-in-c-than-python
Q. Why is reading lines from stdin much slower in C++ than Python?
Q. C++에서 stdin으로 라인 입력 받는 것이 왜 Python 보다 느린가요..


tl;dr: Because of different default settings in C++ requiring more system calls.
TLDR : C++ 가 시스템에 요청하는 디폴트 세팅이 달라서 그렇습니다.

By default, cin is synchronized with stdio, which causes it to avoid any input buffering.
일반적으로, cin은 input 버퍼링을 피하기 위해 stdio와 싱크 되어있습니다.
If you add this to the top of your main, you should see much better performance:
아래의 코드를 main함수위에 작성하면 성능이 더 나아지는 것을 경험할 겁니다.

std::ios_base::sync_with_stdio(false);

Normally, when an input stream is buffered, instead of reading one character at a time, the stream will be read in larger chunks.
일반적으로, 입력 값들을 읽을 때 문자 하나 하나씩 읽지 않고 큰 덩어리로 읽게 됩니다.
This reduces the number of system calls, which are typically relatively expensive.
이것이 비교적 오래 걸리는 시스템을 호출하는 횟수를 줄여줍니다.
However, since the FILE based stdio and iostreams often have separate implementations and therefore separate buffers, this could lead to a problem if both were used together.
하지만, FILE
베이스의 stdio 와 iostreams으 서로 다르게 동작되고 다른 버퍼를 이용합니다. 이로 인해 두 개를 동시에 이요할 경우 문제가 발생할 수 있습니다.
For example:

int myvalue1;
cin >> myvalue1;
int myvalue2;
scanf("%d",&myvalue2);

If more input was read by cin than it actually needed, then the second integer value wouldn't be available for the scanf
function, which has its own independent buffer.
만약 입력 값 중 예상했던 것보다 많이 cin으로 입력을 받으면, 독립적인 버퍼가 필요한scanf로 입력 받으려 했던 두 번째 정수는 받을 수 없을 것입니다.
This would lead to unexpected results.
이러한 것이 예상치 못한 결과로 이끌 수 있죠.
To avoid this, by default, streams are synchronized with stdio.
이를 피하기 위해 디폴트로 streamstdio와 싱크 되어 있습니다.
One common way to achieve this is to have cin read each character one at a time as needed using stdio functions.
cin으로 한 문자씩 입력 받는 것도 하나의 방법입니다.
Unfortunately, this introduces a lot of overhead.
그런데, 이는 많은 오버헤드를 사용합니다.
For small amounts of input, this isn't a big problem, but when you are reading millions of lines, the performance penalty is significant.
입력 값들이 작다면야 괜찮지만, 수백만 줄의 코드를 읽을 경우에 이 문제는 영향을 줍니다.

Fortunately, the library designers decided that you should also be able to disable this feature to get improved performance if you knew what you were doing, so they provided the sync_with_stdio method.
다행히도, 본인이 어떻게 입력을 받아야 하는지 안다면 sync_with_stdio 메소드를 이용해 이러한 속성들이 실행되지 않게 해서 성능을 향상 시킬수 있게 해 놓았습니다.

오버헤드(overhead) : 특정한 목표를 달성하기 위해 간접적 혹은 추가적으로 요구되는 시간, 메모리, 대역폭 혹은 다른 컴퓨터 자원을 말한다.

0개의 댓글