Created
September 7, 2022 21:16
-
-
Save estasney/57b33cefa04fe2442d416c9fbdbbea0b to your computer and use it in GitHub Desktop.
Line Profiler Decorator
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
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