python测试函数的执行性能的方法

2022-03-15 00:00:00 函数 执行 性能

下面的代码用于测试test_function() 函数的性能,可以分析函数的整体性能,函数内每一个方法的执行性能,非常好用。

"""
作者:dfugo(chengang.net@gmail.com)
创建日期:2022/3/15
修改日期:2022/3/15
功能描述:python测试函数执行性能的代码
"""
import profile
import pstats


def test_function():
    print('你好,欢迎访问皮蛋编程:http://www.pidancode.com')


profile.run('test_function()', 'test_function.profile')

pstats.Stats('test_function.profile').sort_stats('time').print_stats()

输出结果如下:

你好,欢迎访问皮蛋编程:http://www.pidancode.com
Tue Mar 15 18:16:11 2022    test_function.profile

         6 function calls in 0.000 seconds

   Ordered by: internal time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.000    0.000 :0(setprofile)
        1    0.000    0.000    0.000    0.000 profile:0(test_function())
        1    0.000    0.000    0.000    0.000 :0(exec)
        1    0.000    0.000    0.000    0.000 :0(print)
        1    0.000    0.000    0.000    0.000 <string>:1(<module>)
        1    0.000    0.000    0.000    0.000 /Users/pidancode/lessons/10.py:12(test_function)
        0    0.000             0.000          profile:0(profiler)

以上代码在Python3.9环境下测试通过。

相关文章