더북(TheBook)
# global_lock_perf.py
import timeit
import threading

trials = 100_000_000
initialized = False
initialized_lock = threading.Lock()
result = timeit.timeit(
    stmt="""
global initialized
# 잠금 없이 사전 검사
if not initialized:
    with initialized_lock:
        # 잠금을 획득한 후 다시 확인
        if not initialized:
            # 비용이 큰 초기화 작업 실행
            ...
            initialized = True
""",
    globals=globals(),
    number=trials,
)

print(f"{result/trials * 1e9:2.1f} 나노초/호출")

 

>>>
5.5 나노초/호출