ROKO

[Python] IO optimization 본문

Develop

[Python] IO optimization

RO_KO 2024. 9. 5. 11:45
728x90

코딩테스트를 준비하면서 입출력을 어떻게 빠르게 받을 수 있을까에 대한 고심을 자주하곤 한다.

이번 기회에 제대로 정리하여 까먹지 않고 이유까지 잘 이해하고 가져가도록 하자.

 

입력

표준 입출력 (stdin)을 사용하게 되면 버퍼에 입력을 임시 저장했다가 전달해주는 과정을 거치게 된다.

 

python에서는 주로 input()을 기본으로 사용하는데 input보다 더 빠른 sys.stdin.readline()을 쓰는것이 좋다.

이유는 input()은 추가적인 프롬프트를 받아 화면에 출력해주는 과정과 내부적으로 개행문자를 매 행마다 제거해주는 연산이 존재하는데 입력을 받는데 약간의 overhead 가 된다.

 

자세한 내용은 아래에 상세히 기술되어 있다.

https://stackoverflow.com/questions/22623528/sys-stdin-readline-and-input-which-one-is-faster-when-reading-lines-of-inpu

 

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

 

하지만 입력을 받을때마다 저 sys.stdin.readline()을 쓰는건 여간 귀찮은 일이 아니다. 이때 우리는 input에 매개변수로 할당시켜 사용할 수 있다.

 

import sys

input = sys.stdin.readline
data = int(input())

위 코드처럼 사용할 수 있다는 뜻이다. 어떻게 이런게 가능할까? 왜냐하면 input(), sys.stdin.readline() 모두 first class object이기 때문이다. 관련 내용을 첨부하겠다.

 

https://velog.io/@rookieand/1-Python-%EC%BD%94%EB%94%A9-%ED%85%8C%EC%8A%A4%ED%8A%B8-%EC%9E%85%EC%B6%9C%EB%A0%A5

 

Python 코딩 테스트 : 입력

이 글은 Python 으로 처음 코딩 테스트를 진행하는 분들께 유용합니다.처음 코딩 테스트 문제를 호기롭게 도전했을 때, 나를 가장 당황스럽게 만들었던 요소는복잡하고 어려운 함수도 아니고, 문

velog.io

https://tibetsandfox.tistory.com/8

 

파이썬(python) - 일급 객체(first-class citizen)

일급 객체(First-class citizen)란? 일급 객체는 OOP에서 사용되는 개념 중 하나로 아래의 조건을 만족하는 객체를 의미합니다. 1. 변수 혹은 데이터 구조(자료구조) 안에 담을 수 있어야 한다. 2. 매개변

tibetsandfox.tistory.com

 

나는 평소에 sys.stdin.readline()을 사용하지만 간간히 os.read()를 활용한 방식을 쓴 코드가 보였다. 이는 테스트 코드 파일 을 직접 받아 사용하는 방식이다.

 

사용법은 아래와 같다.

import os, io, sys
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

https://stackoverflow.com/questions/60594617/fastest-way-to-read-many-inputs-in-pypy3-and-what-is-bytesio-doing-here

 

Fastest way to read many inputs in PyPy3 and what is BytesIO doing here?

Recently I was working on a problem that required me to read many many lines of numbers (around 500,000). Early on, I found that using input() was way too slow. Using stdin.readline() was much bet...

stackoverflow.com

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

 

sys.stdout.write과 print

보통 코딩테스트를 풀때 sys.stdout.write가 print보다 속도가 빠른 이유로 쓰는 경우가 있습니다. 하지만 sys.stdout.write를 쓸 때 주의해야할 점이 있습니다. import time import sys for i in range(10): sys.stdout.writ

coke-mania.tistory.com

 

 

추가자료

각 언어별 입력속도 비교

https://www.acmicpc.net/blog/view/56

 

각 언어별 출력속도 비교

https://www.acmicpc.net/blog/view/57

 

728x90

'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
Comments