Skip to content

Instantly share code, notes, and snippets.

@kristjan-eljand
Created April 19, 2022 11:38
Show Gist options
  • Save kristjan-eljand/e3615a107f01c9e042ba09163997fc84 to your computer and use it in GitHub Desktop.
Save kristjan-eljand/e3615a107f01c9e042ba09163997fc84 to your computer and use it in GitHub Desktop.
Measure the time that the specific python code/function takes and see the results element by element
# Profiler
# cumulative time -- time in function + calls to other functions
# total time -- time only in function without calls to other funs
import cProfile
import pstats
import io
def print_c_profiler(pr, lines_to_print=25):
"""
Create the speed profile of the arbitrary code.
Example usage:
--------
pr = cProfile.Profile()
pr.enable()
[1*i for i in range(1000000)]
pr.disable()
print_c_profile(pr)
"""
s = io.StringIO()
stats = pstats.Stats(pr, stream=s).sort_stats('cumulative')
stats.print_stats(lines_to_print)
print(s.getvalue())
s = io.StringIO()
stats = pstats.Stats(pr, stream=s).sort_stats('tottime')
stats.print_stats(lines_to_print)
print(s.getvalue())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment