DEV Community

Cover image for Profiling Your Python Code
Ngalim Siregar
Ngalim Siregar

Posted on

Profiling Your Python Code

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()
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

pprofiler in action

Discussion (0)