Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import time
- from django.db import connection
- from django.conf import settings
- from contextlib import contextmanager
- def timer(what=None):
- """
- This decorator count the number of seconds
- it takes to run the decorated function.
- It also can be used as a context manager
- """
- # ignore in production
- if not settings.DEBUG:
- return what
- @contextmanager
- def benchmark(name):
- start_time = time.time()
- yield
- secs = time.time() - start_time
- print 'execution of %s: %.2f seconds' % (name, secs)
- if hasattr(what, "__call__"):
- def wrapped_function(*args, **kwargs):
- with benchmark('function "%s"' % what.__name__):
- return what(*args, **kwargs)
- wrapped_function.__doc__ = what.__doc__
- wrapped_function.__name__ = what.__name__
- return wrapped_function
- else:
- return benchmark(('block "%s"' % what) if what else "anonymous block")
- def queries_counter(what=None):
- """
- This decorator count the number of database queries
- performed by Django during the execution of the decorated function.
- It also can be used as a context manager.
- """
- # ignore in production
- if not settings.DEBUG:
- return what
- @contextmanager
- def benchmark(name):
- num_queries_before = len(connection.queries)
- yield
- num_queries = len(connection.queries) - num_queries_before
- print 'execution of %s: %d queries performed' % (name, num_queries)
- if hasattr(what, "__call__"):
- def wrapped_function(*args, **kwargs):
- with benchmark('function "%s"' % what.__name__):
- return what(*args, **kwargs)
- wrapped_function.__doc__ = what.__doc__
- wrapped_function.__name__ = what.__name__
- return wrapped_function
- else:
- return benchmark(('block "%s"' % what) if what else "anonymous block")
- # Usage:
- # @timer
- # def my_function():
- # x = 0
- # for i in range(1, 100000):
- # x += i
- # return x
- #
- # >>> print my_function()
- # execution of function "my_function": 0.02 seconds
- # 4999950000
- # >>> with timer():
- # >>> x = 0
- # >>> for i in range(100000):
- # >>> x += i
- #
- # execution of anonymous block: 0.01 seconds
- # >>> with timer("my block"):
- # >>> x = 0
- # >>> for i in range(100000):
- # >>> x += i
- #
- # execution of block "my block": 0.01 seconds
- # >>> with queries_counter():
- # >>> print Country.objects.count()
- #
- # execution of anonymous block: 1 queries performed
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement