Profiling Python programs with cProfile

February 27, 2024

cProfile is one of the profiling tools built into the standard library. The other two discussed here are hotshot and profile.

Suppose we have the following function.

# loopdemo.py
def foo():
    for a in range(0, 101):
        for b in range(0, 101):
            if a + b == 100:
                yield a, b
if __name__ == '__main__':
    for item in foo():
        print(item)

Run this command:

python3 -m cProfile -s cumulative loopdemo.py

It produces the following output:

    206 function calls in 0.001 seconds
    #在0.01秒内共发生了206次函数调用。包括cProfile的开销。
 
   Ordered by: cumulative time
 
   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.001    0.001 {built-in method builtins.exec}
        1    0.000    0.000    0.001    0.001 loopdemo.py:7(<module>)
      102    0.001    0.000    0.001    0.000 loopdemo.py:7(foo)
      101    0.001    0.000    0.001    0.000 {built-in method builtins.print}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

Here is how to read the columns: ncalls: the number of calls to the function. tottime: the total time spent in the function itself, excluding time spent in functions it calls. percall (first occurrence): tottime divided by ncalls. cumtime: time spent in the function and all its subcalls, from entry through return. percall (second occurrence): the average cumulative time per call, described below in terms of primitive calls. filename:lineno(function): identifies the file, line, and function for the row. cProfile measures whole functions, so its results tell you little about what happens on individual lines within a function.

ncalls for the number of calls.

tottime for the total time spent in the given function (and excluding time made in calls to sub-functions)

percall is the quotient of tottime divided by ncalls

cumtime is the cumulative time spent in this and all subfunctions (from invocation till exit). This figure is accurate even for recursive functions.

percall is the quotient of cumtime divided by primitive calls

filename:lineno(function) provides the respective data of each function

-s cumulative The -s cumulative option tells cProfile to sort functions by cumulative time. It helps me see which parts of the code are slowest.

-o profile.stats Use this option to write the results to a file. The extension can be anything. Here I use .stats because I will read the file from Python later. First run the following command:

python3 -m cProfile -o loopdemo_profile.stats loopdemo.py

Then run this script:

import pstats
p=pstats.Stats("loopdemo_profile.stats")
p.sort_stats("cumulative")
p.print_stats()
p.print_callers()  # 可以显示函数被哪些函数调用
p.print_callees()  # 可以显示哪个函数调用了哪些函数

The output is the same as what the console showed earlier.

         2006 function calls in 0.005 seconds
 
   Ordered by: cumulative time
 
   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.005    0.005 {built-in method builtins.exec}
        1    0.000    0.000    0.005    0.005 loopdemo.py:7(<module>)
     1001    0.004    0.000    0.004    0.000 {built-in method builtins.print}
     1002    0.000    0.000    0.000    0.000 loopdemo.py:30(foo2)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
 
   Ordered by: cumulative time
 
Function                                          was called by...
                                                      ncalls  tottime  cumtime
{built-in method builtins.exec}                   <- 
loopdemo.py:7(<module>)                           <-       1    0.000    0.005  {built-in method builtins.exec}
{built-in method builtins.print}                  <-    1001    0.004    0.004  loopdemo.py:7(<module>)
loopdemo.py:30(foo2)                              <-    1002    0.000    0.000  loopdemo.py:7(<module>)
{method 'disable' of '_lsprof.Profiler' objects}  <- 
 
 
   Ordered by: cumulative time
 
Function                                          called...
                                                      ncalls  tottime  cumtime
{built-in method builtins.exec}                   ->       1    0.000    0.005  loopdemo.py:7(<module>)
loopdemo.py:7(<module>)                           ->    1002    0.000    0.000  loopdemo.py:30(foo2)
                                                        1001    0.004    0.004  {built-in method builtins.print}
{built-in method builtins.print}                  -> 
loopdemo.py:30(foo2)                              -> 
{method 'disable' of '_lsprof.Profiler' objects}  -> 

You can also run cProfile and profile as scripts to profile another script. For example:

python -m cProfile [-o output_file] [-s sort_order] (-m module | myscript.py)

-o writes profiling results to a file instead of standard output.

-s takes one of the sort keys accepted by sort_stats(). It applies only when -o is omitted.

-m profiles a module instead of a script.

  1. The Python Profilers. (n.d.). Python 3.12.2 Documentation. Retrieved February 27, 2024, from https://docs.python.org/3/library/profile.html
  2. Wanderer001. (07 June, 2022.). python性能分析之cProfile模块. CSDN. [Blog post]. Retrieved February 27, 2024, from https://blog.csdn.net/weixin_36670529/article/details/103774677
  3. ElvinYang. (11 May, 2020.). Python 程序性能分析和火焰图. infoQ. [Blog post]. Retrieved February 28, 2024, from https://xie.infoq.cn/article/74483a0917668dc17324d0313

© 2024 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2024-02-27). Profiling Python programs with cProfile. https://caiborui.com/blog/2024-02-27-zh-python%E6%80%A7%E8%83%BD%E5%88%86%E6%9E%90%E6%A8%A1%E5%9D%97cprofile-entrans

@misc{borui2024-a5252889,
  author = {borui},
  title = {{Profiling Python programs with cProfile}},
  year = {2024},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2024-02-27-zh-python%E6%80%A7%E8%83%BD%E5%88%86%E6%9E%90%E6%A8%A1%E5%9D%97cprofile-entrans}
}