Profiling in Python: Who called the function?

后端 未结 8 1828
执念已碎
执念已碎 2020-12-22 15:17

I\'m profiling in Python using cProfile. I found a function that takes a lot of CPU time. How do I find out which function is calling this heavy function the mo

8条回答
  •  温柔的废话
    2020-12-22 16:16

    That may not answer your question directly, but will definitely help. If use the profiler with option --sort cumulative it will sort the functions by cumulative time. Which is helpful to detect not only heavy functions but the functions that call them.

    python -m cProfile --sort cumulative myScript.py
    

    There is a workaround to get the caller function:

    import inspect
    print inspect.getframeinfo(inspect.currentframe().f_back)[2]
    

    You can add as many f_back as you want in case you want the caller caller etc If you want to calculate frequent calls you can do this:

    record = {}
    
    caller = inspect.getframeinfo(inspect.currentframe().f_back)[2]
    record[caller] = record.get(caller, 0) + 1
    

    Then print them by order of frequency:

    print sorted(record.items(), key=lambda a: a[1])
    

提交回复
热议问题