Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added async wrappers to the decorators to work with async functions #250

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 28 additions & 10 deletions memory_profiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import traceback
import warnings
import contextlib
import asyncio

if sys.platform == "win32":
# any value except signal.CTRL_C_EVENT and signal.CTRL_BREAK_EVENT
Expand Down Expand Up @@ -683,14 +684,21 @@ def add_function(self, func):
def wrap_function(self, func):
""" Wrap a function to profile it.
"""

if asyncio.iscoroutinefunction(func):
async def f(*args, **kwds):
self.enable_by_count()
try:
return await func(*args, **kwds)
finally:
self.disable_by_count()
return f

def f(*args, **kwds):
self.enable_by_count()
try:
return func(*args, **kwds)
finally:
self.disable_by_count()

return f

def runctx(self, cmd, globals, locals):
Expand Down Expand Up @@ -1098,14 +1106,24 @@ def profile(func=None, stream=None, precision=1, backend='psutil'):
if not tracemalloc.is_tracing():
tracemalloc.start()
if func is not None:
@wraps(func)
def wrapper(*args, **kwargs):
prof = LineProfiler(backend=backend)
val = prof(func)(*args, **kwargs)
show_results(prof, stream=stream, precision=precision)
return val

return wrapper
if not asyncio.iscoroutinefunction(func):
@wraps(func)
def wrapper(*args, **kwargs):
prof = LineProfiler(backend=backend)
val = prof(func)(*args, **kwargs)
show_results(prof, stream=stream, precision=precision)

return val
return wrapper
else:
@wraps(func)
async def wrapper(*args, **kwargs):
prof = LineProfiler(backend=backend)
val = await prof(func)(*args, **kwargs)
show_results(prof, stream=stream, precision=precision)

return val
return wrapper
else:
def inner_wrapper(f):
return profile(f, stream=stream, precision=precision,
Expand Down