본문 바로가기
PROGRAMMING/PYTHON

[Python] input() vs sys.stdin.readline()

by 안녕나는현서 2021. 8. 16.
728x90

백준 문제를 풀다보면 input()을 사용했을 때 시간초과가 뜨곤 한다.

그럴땐 sys.stdin.readline()을 쓰면 해결되는데, 둘의 차이가 무엇일까?

 

input()

파이썬 공식 문서👇

https://docs.python.org/ko/3/library/functions.html#input

 

input 함수는 파이썬의 내장 함수이다.

input([prompt])
prompt 인자가 있으면, 끝에 개행 문자를 붙이지 않고 표준 출력에 씁니다. 그런 다음 함수는 입력에서 한 줄을 읽고, 문자열로 변환해서 (줄 끝의 줄 바꿈 문자를 제거한다) 돌려줍니다. EOF를 읽으면 EOFError 를 일으킵니다.

 

sys 모듈

파이썬 공식 문서👇

https://docs.python.org/ko/3/library/sys.html#module-sys

 

sys에 속하는 메서드는 file object이다.

그 중에서도 stdin, stout, stderr는 인터프리터의 표준 입력, 출력 및 에러에 사용한다.

sys.stdin
stdin는 모든 대화식 입력에 사용됩니다 (input() 호출을 포함합니다)
sys.stdout
stdout은 print()와 표현식 문장의 출력과 input()의 프롬프트에 사용됩니다
sys.stderror
인터프리터 자신의 프롬프트와 에러 메시지는 stderr로 갑니다.

 

차이점

  1. input()에는 prompt가 존재
    • input()에는 인터프리터가 대화식으로 실행 중인 경우 표시되는 프롬프트가 있다.
    • 이 프롬프트가 비어있어도(기본값), 이로 인해 오버헤드 가 발생한다.
    • (각 readline을 호출하기 전에 프롬프트를 원하는 경우, input이 print보다는 빠름)
  2. input()은 줄 바꿈(개행 문자)을 제거
    • input()은 줄 끝의 줄 바꿈 문자를 제거한다.
    • 어쨌든 줄 바꿈을 제거하려는 경우, sys.stdin.readline().strip()보다는 빠를 수 있다. (??)
  3. 입력의 끝이 표시되는 방식
    • 더 이상 입력이 없는 경우, input()은 EOFError가 발생한다.
    • sys.stdin.readline()은 EOF에서 빈 문자열을 반환한다.

 

결론적으로는 input이 prompt값을 가지고 있고, 개행 문자를 제거한 값을 리턴하기 때문에 느리다는 것이다.

(2번에서 sys.stdin.readline().strip()보다는 빠를 수 있다고 했는데 이건 stackoverflow에 올라온 답변을 번역한거라 자세히 모르겠다..ㅠㅠ)

확실한건 반복문 안에서 여러 줄을 입력받을 때에는 input()보다 sys.stdin.readline()이 빠르다!

 

[출처]

https://stackoverflow.com/questions/22623528/sys-stdin-readline-and-input-which-one-is-faster-when-reading-lines-of-inpu?answertab=votes#tab-top 

 

sys.stdin.readline() and input(): which one is faster when reading lines of input, and why?

I'm trying to decide which one to use when I need to acquire lines of input from STDIN, so I wonder how I need to choose them in different situations. I found a previous post (https://codereview.

stackoverflow.com

 

728x90

댓글