Created
April 16, 2024 20:57
-
-
Save DAVIDhaker/ca401a515ac6c8201c55d2927db9c463 to your computer and use it in GitHub Desktop.
Simple and beautiful code to measure execution time in Python
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
import functools | |
from datetime import datetime | |
class measure_execution_time: | |
""" | |
Декоратор и контекстный менеджер для измерения времени выполнения кода | |
Примеры использования | |
1) | |
@measure_execution_time() | |
def slow_function(): | |
pass | |
Выведет: | |
<function slow_function at 0x7fcb70a21b20> выполнилась за 0:00:03.081997 | |
2) | |
with measure_execution_time("My job"): | |
sleep(1) | |
Выведет: | |
Время выполнения: My job: 0:00:01.000000 | |
""" | |
def __init__(self, name: str = None): | |
self.name = name | |
def __enter__(self): | |
self.started_at = datetime.now() | |
def __exit__(self, exc_type, exc_val, exc_tb): | |
print(f'Время выполнения: {f" {self.name}" if self.name else ""}: {datetime.now() - self.started_at}') | |
def __call__(self, f): | |
""" | |
Декоратор для измерения времени выполнения функции и вывода этого в консоль. | |
""" | |
@functools.wraps(f) | |
def wrapper(*args, **kwargs): | |
started_at = datetime.now() | |
result = f(*args, **kwargs) | |
print(f'{f}{f" ({self.name}) " if self.name else ""} выполнилась за {datetime.now() - started_at}') | |
return result | |
return wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample of usage in real life and Django...