Last active
August 17, 2017 14:46
-
-
Save vadimkantorov/480f7546f9b3f40ba691dbed1ed1f0cb to your computer and use it in GitHub Desktop.
Python tracing and profiling helpers
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
# Bash aliases. | |
# Usage: pytrace my.py --myarg1 | |
# cprofile my.py --myarg1 | |
# lineprofile my.py # requires "pip install line_profiler" | |
# | |
# pytrace() { python -m trace --ignore-dir=$(python -c "import sys, os; print(os.pathsep.join(sys.path))") --trace "$@"; } | |
# cprofile() { python -m cProfile -s cumulative "$@" 2>&1 &> log.txt; } | |
# lineprofile() { python $(python -c 'import kernprof; print(kernprof.__file__.strip("c"))') -l -v "$@"} | |
def pytrace(func): | |
import trace, functools, sys, os | |
def wrapper(*args, **kwargs): | |
tracer = trace.Trace(count=True, trace=False, ignoredirs = [sys.prefix, sys.exec_prefix], outfile = 'outfile.cover') | |
res = tracer.runfunc(func, *args, **kwargs) | |
tracer.results().write_results(coverdir = '.') | |
print(open(sys.modules[func.__module__].__file__.replace('.py', '.cover')).read()) | |
for file_name in os.listdir('.'): | |
if file_name.endswith('.cover'): | |
os.remove(file_name) | |
return res | |
return functools.wraps(func)(wrapper) | |
def cprofile(func, sort = 'tottime'): | |
import cProfile, functools | |
def wrapper(*args, **kwargs): | |
profiler = cProfile.Profile() | |
profiler.enable() | |
res = func(*args, **kwargs) | |
profiler.disable() | |
profiler.print_stats(sort=sort) | |
return res | |
return functools.wraps(func)(wrapper) | |
def lineprofile(func): | |
import line_profiler, functools | |
def wrapper(*args, **kwargs): | |
profiler = line_profiler.LineProfiler() | |
res = profiler(func)(*args, **kwargs) | |
profiler.print_stats() | |
return res | |
return functools.wraps(func)(wrapper) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment