[Python] 파이썬 빠르게 반복 입력 받기 (sys.stdin.readline)

2022. 12. 25. 17:51Python

반응형

일반적으로 파이썬을 통해 입력을 받을 때에는 파이썬 내장 함수인 input()을 통해 입력을 받지만, 알고리즘 문제를 풀다 보면 이걸 사용했을 때 속도가 너무 느려 시간 초과가 발생한다. 이때 sys모듈의 stdin을 활용하면 더 빠르게 input을 받을 수 있다. 근데 둘이 어떤 차이가 있어서 이렇게까지 차이가 나는지 한번 찾아봤다.

 

input() VS sys.stdin모듈

input()

파이썬의 내장함수로, 파이썬에서 입력을 받는데에 사용되는 기본적인 함수이다.

물론, 이건 그냥 내가 설명하는 말이고, 파이썬3의 공식문서에 나와있는 설명은 이렇다.

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised. 

공식문서: https://docs.python.org/3/library/functions.html?highlight=input#input

즉, input()의 실행과정을 보면

입력으로부터 한 줄을 읽는다 → newline문자 제거(\n) →문자열 변환 →함수 종료 (return)

이라는 뜻이된다.

 

sys.stdin

파이썬 공식문서 상의 설명은 이렇다.

File objects used by the interpreter for standard input, output and errors:
● stdin is used for all interactive input (including calls to input());
● stdout is used for the output of print() and expression statements and for the prompts of input();
● The interpreter’s own prompts and its error messages go to stderr.

These streams are regular text files like those returned by the open() function.

https://docs.python.org/3/library/sys.html?highlight=sys%20stdin#sys.stdin

즉, sys.stdin을 통해 받는 입력은 텍스트 파일을 버퍼로 읽어들여, 일반적인 텍스트 파일을 불러오는 것과 같은 과정을 거친다는 뜻이다.

 

 

비교

결론적으로, 복잡한 과정을 거치며 문자열단위로 변환시키는 input()보다 버퍼를 통해 한 번에 값을 읽어오는 sys.stdin이 훨씬 빠르게 동작한다.

 

사용법

  • import
from sys import stdin
  • 한 줄 입력
x = sys.stdin.readline()
  • input()처럼 사용하고 싶은 경우
def input():
    return stdin.readline().rstrip() #rstrip()은 우측 공백 제거

x= input()

input()함수를 overwrite하여 평소 input()을 사용하듯이 코드를 작성할 수 있다.


알고리즘 문제를 파이썬으로 풀어보기 시작한 지 얼마 안돼서 몰랐는데, 시간 차이가 생각보다 심해서 놀랐다.

 

지식이 늘었다.

 

반응형