Python time.sleep() 완전 정복: 모범 사례, 멀티스레딩, 실전 예제
Python time.sleep()
time.sleep()은 지정된 초 수만큼 현재 스레드를 일시 정지합니다.
Python의 time 모듈은 시간 작업을 위한 다양한 유틸리티를 제공합니다. 그중 time.sleep()은 의도적인 지연 추가, 스레드 동기화, 작업 스로틀링에 필수적입니다.
예제 1: 기본 사용법
import time
print("즉시 출력됨.")
time.sleep(2.4)
print("2.4초 후에 출력됨.")
이 간단한 스크립트는 time.sleep()이 부동소수점 인수를 허용함을 보여줍니다. Python 3.5 이상에서는 함수가 최소 절전 시간을 보장하며, 이전 버전에서는 약간 더 오래 잘 수 있습니다.
예제 2: 디지털 시계
import time
while True:
local = time.localtime()
print(time.strftime("%I:%M:%S %p", local))
time.sleep(1)
루프가 매초 현재 로컬 시간을 출력합니다. 터미널이 지저분해지는 것을 방지하기 위해 같은 줄을 업데이트하는 개선된 버전:
import time
while True:
local = time.localtime()
print(time.strftime("%I:%M:%S %p", local), end="", flush=True)
print("\r", end="", flush=True)
time.sleep(1)
자세한 내용은 Python time.sleep() 문서를 참조하세요.
스레드 이해하기
프로세스는 실행 중인 프로그램이며, 스레드는 해당 프로세스 내의 가벼운 단위입니다. 여러 스레드가 동시에 실행되며 같은 메모리 공간을 공유합니다.
예제 3: 간단한 멀티스레딩
import threading
def greet_hello():
for _ in range(3):
print("Hello")
def greet_hi():
for _ in range(3):
print("Hi")
t1 = threading.Thread(target=greet_hello)
t2 = threading.Thread(target=greet_hi)
t1.start()
t2.start()
t1과 t2가 동시에 실행되므로 실행할 때마다 출력 순서가 달라질 수 있습니다.
멀티스레드 환경에서 time.sleep()
단일 스레드 프로그램에서 time.sleep()은 전체 프로세스를 중단합니다. 멀티스레드 환경에서는 호출한 스레드만 일시 정지되어 다른 스레드가 계속 실행됩니다.
예제 4: 스레드를 다르게 일시 정지
import threading, time
def say_hello():
for _ in range(4):
time.sleep(0.5)
print("Hello")
def say_hi():
for _ in range(4):
time.sleep(0.7)
print("Hi")
t1 = threading.Thread(target=say_hello)
t2 = threading.Thread(target=say_hi)
t1.start()
t2.start()
한 스레드는 0.5초, 다른 스레드는 0.7초 동안 대기하며 독립적인 페이싱을 보여줍니다.
스레딩에 대한 자세한 내용은 Python threading 모듈을 참조하세요.