Created
March 29, 2019 19:27
-
-
Save mmasashi/e90195ca2b119f4eb1606ff40d1bf2ff to your computer and use it in GitHub Desktop.
Python cProfile template
This file contains 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 contextlib | |
import cProfile | |
import datetime | |
import io | |
import pstats | |
import time | |
def log(msg): | |
cur_datetime_str = datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S') | |
print(f'{cur_datetime_str} {msg}') | |
@contextlib.contextmanager | |
def take_profile(): | |
pr = cProfile.Profile() | |
pr.enable() | |
log('################ Calling the target function ################') | |
try: | |
yield | |
finally: | |
log('################ Finished the target function ################') | |
pr.disable() | |
s = io.StringIO() | |
sortby = 'cumulative' | |
ps = pstats.Stats(pr, stream=s).sort_stats(sortby) | |
ps.print_stats() | |
print(s.getvalue()) | |
def target_logic(): | |
# Write a target logic here | |
print('Processing something') | |
def main(): | |
start_time = time.time() | |
with take_profile(): | |
target_logic() | |
elapsed_time = time.time() - start_time | |
log('-> Done ({})'.format(elapsed_time)) | |
if __name__ == '__main__': | |
main() |
This file contains 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
$ python3 cprofile_template.py | |
2019-03-29T12:25:09 ################ Calling the target function ################ | |
Processing something | |
2019-03-29T12:25:09 ################ Finished the target function ################ | |
14 function calls in 0.000 seconds | |
Ordered by: cumulative time | |
ncalls tottime percall cumtime percall filename:lineno(function) | |
2 0.000 0.000 0.000 0.000 cprofile_template.py:24(log) | |
3 0.000 0.000 0.000 0.000 {built-in method builtins.print} | |
2 0.000 0.000 0.000 0.000 {method 'strftime' of 'datetime.date' objects} | |
1 0.000 0.000 0.000 0.000 /usr/local/Frameworks/Python.framework/Versions/3.7/lib/python3.7/contextlib.py:116(__exit__) | |
1 0.000 0.000 0.000 0.000 {built-in method builtins.next} | |
1 0.000 0.000 0.000 0.000 cprofile_template.py:6(take_profile) | |
2 0.000 0.000 0.000 0.000 {built-in method now} | |
1 0.000 0.000 0.000 0.000 cprofile_template.py:29(target_logic) | |
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} | |
2019-03-29T12:25:09 -> Done (0.0015227794647216797) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment