zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python的N种性能测试工具(timeit、profile、cProfile、line_profiler、memory_profiler、objgraph、Pyinstrument、PyCharm)

PythonPycharm性能 memory 测试工具 line Profile Profiler
2023-09-11 14:15:15 时间

1、timeit

        timeit只输出被测试代码的总运行时间,单位为秒,没有详细的统计。

示例代码:

import timeit


def fun():
    lst = []
    for i in range(100000):
        lst.append(i * i)


print(timeit.timeit('fun()', 'from __main__ import fun', number=1))
print(timeit.timeit('fun()', 'from __main__ import fun', number=100))

运行结果:

2、profile

profile:纯Python实现的性能测试模块,接口和cProfile一样。

示例代码:

import profile


def fun():
    lst = []
    for i in range(100000):
        lst.append(i * i)


print(profile.run('fun()'))

运行结果:

参数解析:

  • ncall:函数运行次数
  • tottime: 函数的总的运行时间,减去函数中调用子函数的运行时间
  • 第一个percall:percall = tottime / nclall
  • cumtime:函数及其所有子函数调整的运行时间,也就是函数开始调用到结束的时间。
  • 第二个percall:percall = cumtime / nclall 

3、cProfile

        c语言实现的性能测试模块,接口和profile一样。

示例代码:

import cProfile


def fun():
    lst = []
    for i in range(100000):
        lst.append(i * i)


print(cProfile.run('fun()'))

运行结果:

参数解析:

        ncalls、tottime、percall、cumtime含义同profile。

4、line_profiler

        略

5、memory_profiler

        略

6、objgraph

        略

7、Pyinstrument

详见博文:python中代码性能分析Pyinstrument库_IT之一小佬的博客-CSDN博客

8、PyCharm图形化性能测试工具

详见博文:PyCharm的Profile工具进行python代码性能分析_IT之一小佬的博客-CSDN博客

参考博文:

Python的7种性能测试工具:timeit、profile、cProfile、line_profiler、memory_profiler、PyCharm图形化性能测试工具、objgraph_xiemanR的博客-CSDN博客_python cprofile flask