ROKO
[Python] IO optimization 본문
코딩테스트를 준비하면서 입출력을 어떻게 빠르게 받을 수 있을까에 대한 고심을 자주하곤 한다.
이번 기회에 제대로 정리하여 까먹지 않고 이유까지 잘 이해하고 가져가도록 하자.
입력
표준 입출력 (stdin)을 사용하게 되면 버퍼에 입력을 임시 저장했다가 전달해주는 과정을 거치게 된다.
python에서는 주로 input()을 기본으로 사용하는데 input보다 더 빠른 sys.stdin.readline()을 쓰는것이 좋다.
이유는 input()은 추가적인 프롬프트를 받아 화면에 출력해주는 과정과 내부적으로 개행문자를 매 행마다 제거해주는 연산이 존재하는데 입력을 받는데 약간의 overhead 가 된다.
자세한 내용은 아래에 상세히 기술되어 있다.
하지만 입력을 받을때마다 저 sys.stdin.readline()을 쓰는건 여간 귀찮은 일이 아니다. 이때 우리는 input에 매개변수로 할당시켜 사용할 수 있다.
import sys
input = sys.stdin.readline
data = int(input())
위 코드처럼 사용할 수 있다는 뜻이다. 어떻게 이런게 가능할까? 왜냐하면 input(), sys.stdin.readline() 모두 first class object이기 때문이다. 관련 내용을 첨부하겠다.
https://tibetsandfox.tistory.com/8
나는 평소에 sys.stdin.readline()을 사용하지만 간간히 os.read()를 활용한 방식을 쓴 코드가 보였다. 이는 테스트 코드 파일 을 직접 받아 사용하는 방식이다.
사용법은 아래와 같다.
import os, io, sys
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
https://codeforces.com/blog/entry/83441
출력
출력의 경우 print()보다 sys.stdout.write()를 사용하면 더 빠르다. 왜냐하면 print()는 개행문자를 자동적으로 삽입해주는 과정에서 overhead가 발생하기 때문이다.
import sys
print = sys.stdout.write
data = "hello"
print(data + "\n")
하지만 write를 사용할때 주의해야할 점이 있다. 아래 블로그에 자세히 설명되어 있으니 꼭! 확인하고 쓰도록 하자.
https://coke-mania.tistory.com/70
추가자료
각 언어별 입력속도 비교
https://www.acmicpc.net/blog/view/56
각 언어별 출력속도 비교
https://www.acmicpc.net/blog/view/57
'Develop' 카테고리의 다른 글
[Linux] Python process 강제 종료 (0) | 2024.07.15 |
---|---|
[Mac] Vscode module, import error (0) | 2023.08.13 |
[Mac] python 3.7 install error (0) | 2023.06.13 |
[Mac] vscode terminal branch info 설정 (0) | 2023.05.07 |