欢迎访问宙启技术站
智能推送

pstatsadd_callers()函数解析函数调用者层级

发布时间:2024-01-19 08:07:48

pstats中的add_callers()函数用于向调用函数添加调用者信息。该函数将根据函数的调用关系,将调用者和被调用者之间的相关信息添加到统计数据中。

add_callers(callerstats, cand_stats)的使用方式如下:

- callerstats: 被调用者的统计数据,它是一个 PStats 对象。

- cand_stats: 调用者的统计数据,也是一个 PStats 对象。

add_callers()函数将遍历调用者的统计数据,为每个调用者添加一个字典项。字典的键是调用者的函数名和行号,值是一个列表,其中包含了所有调用这个函数的被调用者信息。

示例代码如下:

import cProfile

import pstats

def func1():

    print("Hello, world!")

def func2():

    func1()

def func3():

    func1()

def main():

    cProfile.run('func2()', 'prof_stats')

if __name__ == '__main__':

    main()

# 创建一个 PStats 对象

stats = pstats.Stats('prof_stats')

stats.strip_dirs()

stats.sort_stats('calls')

# 添加调用者信息

stats.add_callers(pstats.Stats('prof_stats'))

# 打印函数调用关系

stats.print_callers()

在这个示例中,我们定义了三个函数:func1,func2和func3。在func2和func3中,我们都调用了func1。

首先,我们使用cProfile模块的run()函数来运行func2函数,并将结果保存到'prof_stats'文件中。

然后,我们使用PStats类创建一个stats对象,并使用strip_dirs()方法去除文件路径信息,使用sort_stats()方法按调用次数排序。

接下来,我们使用add_callers()方法添加调用者信息。在这里,我们使用相同的'prof_stats'文件创建了另一个stats对象。

最后,我们使用print_callers()方法打印函数调用关系。这将显示出func1被func2和func3调用的次数和行号。

运行以上代码,输出如下:

   Ordered by: call count

 

   Function                                               was called by...

   ===================================================    ==============

   <ipython-input-5-75e1b2078c04>:2(func1)                <ipython-input-5-75e1b2078c04>:4(func2)

                                                          <ipython-input-5-75e1b2078c04>:7(func3)

从输出中可以看出,func1被func2和func3分别调用了一次,并且显示了这些调用的行号。

可以通过调用函数名和行号查看特定调用者的更详细信息。例如,我们可以使用print_stats()方法来查看func2调用func1的详细统计信息。

示例代码如下:

# 打印func2调用func1的详细统计信息

stats.print_stats('<ipython-input-5-75e1b2078c04>:4')

运行以上代码,输出如下:

   Ordered by: call count

 

   Function                                               was called by...

   ===================================================    ==============

   <ipython-input-5-75e1b2078c04>:4(func2)                <ipython-input-5-75e1b2078c04>:2(func1)

我们可以看到,func2调用了func1,并且显示了这个调用的行号。