Skip to content

Instantly share code, notes, and snippets.

@gottadiveintopython
Last active July 24, 2022 00:58
Show Gist options
  • Save gottadiveintopython/3171796d8e665d1d7ed7bce8f8a7c06f to your computer and use it in GitHub Desktop.
Save gottadiveintopython/3171796d8e665d1d7ed7bce8f8a7c06f to your computer and use it in GitHub Desktop.
class-based context managers are faster than generator-based ones
# 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