sys.stdout.write과 print
보통 코딩테스트를 풀때 sys.stdout.write
가 print
보다 속도가 빠른 이유로 쓰는 경우가 있습니다.
하지만 sys.stdout.write
를 쓸 때 주의해야할 점이 있습니다.
import time
import sys
for i in range(10):
sys.stdout.write(str(i))
time.sleep(1)
위와 같은 코드를 실행할 때 어떻게 출력이 될거 같으신가요?
1초마다 0, 1, 2, 3 .. 순서대로 출력이 될 거 같습니다.
하지만 출력해보면 10초 후 0,1,2,3.. 이 한꺼번에 출력됨을 볼 수 있습니다.
위 현상을 해결하려면
sys.stdout.write
를 호출 한 후 바로 sys.stdout.flush()
를 호출해주거나
print
로 변경하면 됩니다. print
는 내부에서 sys.stdout.write
를 호출 한 후 바로 sys.stdout.flush()
를 호출해줍니다.
import time
import sys
for i in range(10):
sys.stdout.write(str(i))
# sys.stdout.flush()
# or print(i)
time.sleep(1)
이러한 현상이 일어나는 이유는
sys.stdout.write('1')을 호출하면 '1'을 바로 호출하는것이 아니라 '1' 을 buffer에 저장하고, sys.stdout.flush() 가 일어날때 화면에 출력하게 됩니다.
flush
가 일어나기전에는 계속 buffer
에 남아있는것 입니다.
sys.stdout.flush()
는 기본적으로 프로그램이 종료될 때 또한 호출되기 때문에 간단한 프로그램에서는 느낄 수 없었지만 프로그램이 끝나지 않고 계속 도는경우 이러한 현상때문에 문제가 발생할 수도 있을거 같습니다.
https://brunch.co.kr/@sinclairo/12
함수와 표준 I/O
내가 그의 이름을 불러 주었을 때 III | Buffering과 Stream이라는 시냇물 우리가 표준 입출력함수들과 더불어 알아야 할 것은 표준 입출력 Stream입니다. 쉽게 말해 Stream은 시냇물이고, 잘 알다시피 우
brunch.co.kr
https://stackoverflow.com/questions/10019456/usage-of-sys-stdout-flush-method
Usage of sys.stdout.flush() method
What does sys.stdout.flush() do?
stackoverflow.com