return 키워드 | yield 키워드 |
---|---|
모든 결과값을 메모리에 올려놓음 | 결과 값을 하나씩 메모리에 올려놓음 |
결과값을 한번에 제공 | 결과값을 여러 번 나누어서 제공 |
import time
def get_char(target_str):
result = []
for ch in target_str:
time.sleep(1)
result.append(ch)
return result
def get_char_using_yield(target_str):
for ch in target_str:
time.sleep(1)
yield ch
target_str = "hello"
for ch in get_char(target_str):
start_time = time.time()
print(ch)
print(f"실행시간: {start_time:.2f}")
print("Using generator")
for ch in get_char_using_yield(target_str):
start_time_using_yield = time.time()
print(ch)
print(f"실행시간: {start_time_using_yield:.2f}")
get_char 함수를 실행하였을 때는 함수 실행이 끝난 후 print 문이 수행되므로 print 구문 실행 시간에 차이가 거의 없음을 확인할 수 있습니다.
반면에, get_char_using_yield 함수를 실행 시에는 yield 구문으로 값이 반환될 때마다 print 구문이 실행되므로, 1초 간격으로 순차적으로 수행됨을 확인할 수 있습니다.
참고문헌