Skip to content

Commit 8faeb84

Browse files
Add small utility to profile any function
1 parent 71efa79 commit 8faeb84

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

profiling/profiling.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import functools
2+
3+
from pyinstrument.profiler import Profiler
4+
5+
6+
def profile_function(output_file="profile.html"):
7+
"""
8+
Profiles a function execution time.
9+
10+
Parameters
11+
----------
12+
output_file: file to write profile output. Defaults to "profile.html".
13+
"""
14+
15+
def decorator(function):
16+
@functools.wraps(function)
17+
def wrapper(*args, **kwargs):
18+
profiler = Profiler()
19+
profiler.start()
20+
result = function(*args, **kwargs)
21+
profiler.stop()
22+
output = profiler.output_html()
23+
with open(output_file, "w") as f:
24+
f.write(output)
25+
return result
26+
27+
return wrapper
28+
29+
return decorator

test_requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,4 @@ coverage>=6.4.4
77
flake8>=3.9.2
88
isort>=5.8.0
99
mypy>=0.740
10+
pyinstrument>=4.4.0

0 commit comments

Comments
 (0)