Skip to content

Instantly share code, notes, and snippets.

@estasney
Created September 7, 2022 21:16
Show Gist options
  • Save estasney/57b33cefa04fe2442d416c9fbdbbea0b to your computer and use it in GitHub Desktop.
Save estasney/57b33cefa04fe2442d416c9fbdbbea0b to your computer and use it in GitHub Desktop.
Line Profiler Decorator
import atexit
_PROFILER = None
def get_stats():
global _PROFILER
if _PROFILER is None:
print("No Profiler")
return
# noinspection PyUnresolvedReferences
_PROFILER.print_stats()
def profile(func):
"""
Called as decorator.
Line-by-line profiling will be printed to stdout at process end
Examples
----------
```python
@profile
def f1(x):
x += 1
return x
```
"""
global _PROFILER
if _PROFILER is None:
try:
from line_profiler import LineProfiler
_PROFILER = LineProfiler()
except ImportError:
return func
_PROFILER.add_function(func)
_PROFILER.enable_by_count()
atexit.register(get_stats)
return func
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment