Last active
February 23, 2025 08:14
-
-
Save gottadiveintopython/3171796d8e665d1d7ed7bce8f8a7c06f to your computer and use it in GitHub Desktop.
クラスで実装されたコンテキストマネージャーの方がジェネレーターの物より速い
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# CPython3.8.12 上で測ったところclass-basedの方が17倍近く速かった | |
from functools import partial | |
from contextlib import contextmanager | |
from timeit import timeit | |
class class_based: | |
__slots__ = tuple() | |
def __enter__(self): | |
pass | |
def __exit__(self, exc_type, exc_val, exc_tb): | |
pass | |
@contextmanager | |
def generator_based(): | |
yield | |
def use_context_manager(context_manager): | |
with context_manager(): | |
pass | |
t_class = timeit(partial(use_context_manager, class_based)) | |
t_generator = timeit(partial(use_context_manager, generator_based)) | |
print(f"{t_class = }") | |
print(f"{t_generator = }") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment