Search code examples
pythonperformance-testingcall-graph

How to remove library modules or specific functions from pycallgraph


I am using pycallgraph to analyze my code performance. However, the call graph is pretty messy with many calls to system functions as well as certain functions I would not like to document. How can I stop pycallgraph from reporting these calls?


Solution

  • Pycallgraph provides filtering capabilities to filter out any module, class or function you would like to exclude from call graph. Following function should be defined before you start the trace and passed to pycallgraph

    Example

    def filtercalls(call_stack, modul, clas, func, full):
        mod_ignore = ['shutil','scipy.optimize','re','os','sys','json']
        func_ignore = ['CustomFunctionName','pdbcall']
        clas_ignore = ['pdb']
        return modul not in mod_ignore and func not in func_ignore and clas not in clas_ignore
    

    The pycallgraph trace start is

    pycallgraph.start_trace(filter_func=filtercalls)
    

    This way, any module, class or function you provide in filtercalls will be removed. Please note that many time in standard libraries providing just the module name is not enough. Thus, including numpy in mod_ignore will still result in numpy.core being included