Created
March 10, 2022 15:00
-
-
Save valeriiduz/2b86f23ae1a09889bc6733b06c01259b to your computer and use it in GitHub Desktop.
Profilers for check how much time spend method or funtion
This file contains 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 cProfile | |
import datetime | |
import logging | |
from functools import wraps | |
from inspect import isclass | |
from django.conf import settings | |
logger = logging.getLogger(__name__) | |
def cprofile(function): | |
""" | |
Decorator for profile functions or methods by | |
cProfile library and print output to stdout output | |
""" | |
@wraps(function) | |
def wrapper(*args, **kwargs): | |
if settings.CODE_PROFILER: | |
profile = cProfile.Profile() | |
result = profile.runcall(function, *args, **kwargs) | |
profile.print_stats() | |
else: | |
result = function(*args, **kwargs) | |
return result | |
return wrapper | |
def profile(function): | |
""" | |
Decorator for calculate executing time of functions or methods | |
and print output to stdout output | |
""" | |
@wraps(function) | |
def wrapper(*args, **kwargs): | |
if settings.CODE_PROFILER: | |
started_at = datetime.datetime.utcnow() | |
result = function(*args, **kwargs) | |
executed_seconds = (datetime.datetime.utcnow() - started_at).seconds | |
logger.info("PROCESSED %s %s %s %s seconds were executed", | |
args[0].request_id, args[0], | |
function.__name__, executed_seconds) | |
else: | |
result = function(*args, **kwargs) | |
return result | |
return wrapper | |
def decorate_class_methods(decorator, expose=("__init__",)): | |
""" | |
Add custom decorator for each method of a class | |
""" | |
def decorate(cls): | |
for attr in cls.__dict__: | |
if not isclass(getattr(cls, attr)) and \ | |
callable(getattr(cls, attr)) and attr not in expose: | |
setattr(cls, attr, decorator(getattr(cls, attr))) | |
return cls | |
return decorate |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment