Profiling Your Python Code
Ngalim Siregar
Posted on January 5, 2022
Sometimes you want to profile just a single function in your Python program. To profile single function on Python program, we can use cProfile
to profile single function
def create_array():
arr=[]
for i in range(0,400000):
arr.append(i)
def print_statement():
print('Array created successfully')
def main():
create_array()
print_statement()
if __name__ == '__main__':
import cProfile, pstats
profiler = cProfile.Profile()
profiler.enable()
main()
profiler.disable()
stats = pstats.Stats(profiler).sort_stats('ncalls')
stats.print_stats()
That will profile method create_array
and print_statement
. By using pprofiler
library we can simplify those step to single decorator call
from pprofiler import pprof
...
@pprof()
def main():
create_array()
print_statement()
if __name__ == '__main__':
main()
By default pprofiler
will sort by ncalls
, we can use other sorting key by define it.
from pprofiler import pprof
...
@pprof(sort_by='time')
def main():
create_array()
print_statement()
if __name__ == '__main__':
main()
💖 💪 🙅 🚩
Ngalim Siregar
Posted on January 5, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.