Python 关于运行时间、调用次数及内存使用的性能测试

简介: Python 关于运行时间、调用次数及内存使用的性能测试

Python是一种解释性的语言,执行速度相比C、C++等语言比较缓慢;我们需要在其它地方上下功夫来提高代码的执行速度。首先需要对代码进行分析,这个时候则需要用一些性能测试工具

30358c5d1a54471e81eabf7831114250.png



一、 Module time


time.time

最普通的手段就是时间之差,其它编程语言中也都会到过此方法:

>>> from time import time
>>> def fib(n):
  if n<3:return 1
  return fib(n-1)+fib(n-2)
>>> t = time(); fib(30); time()-t
832040
0.4218752384185791
>>> t = time(); fib(35); time()-t
9227465
4.656255722045898
>>> t = time(); fib(40); time()-t
102334155
51.281249046325684
>>> 


斐波那契数列未改进的递归是比较耗时的,就专门以它为例了。

除time()函数外,时间库里可用来计时的函数有很多,还成对的(_ns后缀的以纳秒为单位):

time.time()
time.time_ns()
time.monotonic()
time.monotonic_ns()
time.perf_counter()
time.perf_counter_ns()
time.process_time()
time.process_time_ns()
time.thread_time()
time.thread_time_ns()



区别一:


time 时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量

monotonic 表示的是从操作系统的启动时间开始按秒计算的偏移量

perf_counter 表示的是从程序的启动时间开始按秒计算的偏移量,如下面所举的例子中,它的返回值(613.323613)表示Python IDLE Shell窗口打开的时间。


如把perf_counter()放在源程序未尾结束处(比如放在语句_exit(0)前)就不用计算差值,返回的时间就是程序从启动到退出的时间。

>>> from time import time,monotonic,perf_counter
>>> time()
1633249386.5061808
>>> monotonic()
4594.25
>>> perf_counter()
613.323613
>>> 



区别二:

处理进程、线程时间的不受sleep影响

>>> from time import time,sleep,process_time,thread_time
>>> def fib(n):
  if n<3:return 1
  return fib(n-1)+fib(n-2)
>>> t = time(); fib(30); time()-t
832040
0.432178258895874
>>> t = thread_time(); fib(30); thread_time()-t
832040
0.421875
>>> t = time(); sleep(1); fib(30); sleep(1); time()-t
832040
2.463411569595337
>>> t = process_time(); sleep(1); fib(30); sleep(1); process_time()-t
832040
0.421875
>>> t = thread_time(); sleep(1); fib(30); sleep(1); thread_time()-t
832040
0.4375
>>> 



二、 Module timeit

比较适合测试小段代码:

>>> from timeit import timeit
>>> timeit(stmt='a=10;b=10;sum=a+b')
0.11455389999997578
>>> timeit(stmt='a=10;b=10;sum=a+b',number=10000)
0.0013638000000355532
>>> 


程序中的使用如下:

import timeit
def fib(n):
    if n<3:return 1
    return fib(n-1)+fib(n-2)
if __name__ == '__main__':
    tm = timeit.Timer('fib(40)', 'from __main__ import fib')
    print(tm.timeit(1))


注意: .timeit() 的参数number默认值为1000000,上例中tm.timeit()不用参数的话停不了


   这个模块还能在DOS命令窗口下执行:

D:\>python -m timeit -n 30 -s "import random" "[random.random() for i in range(100000)]"
    30 loops, best of 5: 23.1 msec per loop




三、 Module cProfile


这个模块除了给出调用时间,还报告函数调用次数:

>>> from cProfile import Profile
>>> f = lambda n:1 if n<3 else f(n-1)+f(n-2)
>>> cp = Profile()
>>> cp.enable(); n = f(30); cp.disable()
>>> cp.print_stats()
         1664081 function calls (3 primitive calls) in 1.007 seconds
   Ordered by: standard name
   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
1664079/1    1.007    0.000    1.007    1.007 <pyshell#70>:1(<lambda>)
        1    0.000    0.000    0.000    0.000 rpc.py:614(displayhook)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
>>> 2*f(30)-1
1664079
>>> 



为什么f(30)的调用次数ncalls = 2*f(30)-1,因为我用傻办法验证过所以我知道。

这个模块还能在DOS命令窗口下执行:

D:\>python -m cProfile -s cumulative test1.py
         350 function calls (343 primitive calls) in 0.002 seconds
   Ordered by: cumulative time
   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
      3/1    0.000    0.000    0.002    0.002 {built-in method builtins.exec}
        1    0.000    0.000    0.002    0.002 test1.py:1(<module>)
      2/1    0.000    0.000    0.002    0.002 <frozen importlib._bootstrap>:986(_find_and_load)
      2/1    0.000    0.000    0.002    0.002 <frozen importlib._bootstrap>:956(_find_and_load_unlocked)
      2/1    0.000    0.000    0.001    0.001 <frozen importlib._bootstrap>:650(_load_unlocked)
        2    0.000    0.000    0.001    0.000 <frozen importlib._bootstrap>:890(_find_spec)
        1    0.000    0.000    0.001    0.001 <frozen importlib._bootstrap_external>:777(exec_module)
        1    0.000    0.000    0.001    0.001 <frozen importlib._bootstrap_external>:1334(find_spec)
        1    0.000    0.000    0.001    0.001 <frozen importlib._bootstrap_external>:1302(_get_spec)
        4    0.000    0.000    0.001    0.000 <frozen importlib._bootstrap_external>:1431(find_spec)
        6    0.000    0.000    0.001    0.000 <frozen importlib._bootstrap_external>:80(_path_stat)
        6    0.001    0.000    0.001    0.000 {built-in method nt.stat}

...........省略很多行..........




四、 Module line_profiler


运行时间逐行分析报告,测试文件test1.py源码如下:

@profile
def fib(n):
    if n<3:return 1
    return fib(n-1)+fib(n-2)
if __name__ == '__main__':
    print(fib(30))


不用import导入,只在测试函数前加上装饰器 @profile ,测试在DOS窗口进行:

D:\>kernprof -l -v test1.py
832040
Wrote profile results to test1.py.lprof
Timer unit: 1e-06 s
Total time: 3.07291 s
File: test1.py
Function: fib at line 1
Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     1                                           @profile
     2                                           def fib(n):
     3   1664079    1341610.0      0.8     43.7      if n<3:return 1
     4    832039    1731304.5      2.1     56.3      return fib(n-1)+fib(n-2)
D:\>



五、Module memory_profiler


内存使用逐行分析报告,使用方法基本同上还是测试test1.py,命令如下:

D:\>python -m memory_profiler test1.py
832040
Filename: test1.py
Line #    Mem usage    Increment  Occurences   Line Contents
============================================================
     1   29.203 MiB -139766.219 MiB     1664079   @profile
     2                                         def fib(n):
     3   29.203 MiB -139795.418 MiB     1664079       if n<3:return 1
     4   29.203 MiB -69899.141 MiB      832039       return fib(n-1)+fib(n-2)




六、Module guppy


查看对象占用的堆内存大小


此模块安装时碰到:

error: Microsoft Visual C++ 14.0 is required. Get it with "Build Tools for Visual Studio": https://visualstudio.microsoft.com/downloads/

需要VC++14,所以没装没能亲测,大致用法:



 from guppy import hpy
    import gc
    hp = hpy()
    ast = parse_file('filename')
    gc.collect()
    h = hp.heap()
    print(h)


以上涉及的所有模块,都可以在dos窗口下验证有无或者在线安装:

    D:\>pip show xxModule
    WARNING: Package(s) not found: xxModule
    D:\>pip install xxModule


最后,说一下模块这个英文单词 module,我之前一直读成 “妈逗”,大概受了单词 model 的影响。今天我查了字典,才知道module应该读作“妈舅” ^_^

你是怎么读的呢? 读对的请点赞!读错的请点收藏!!没想过怎么读的点一键三连!!!

目录
相关文章
|
22天前
|
传感器 数据采集 监控
Python生成器与迭代器:从内存优化到协程调度的深度实践
简介:本文深入解析Python迭代器与生成器的原理及应用,涵盖内存优化技巧、底层协议实现、生成器通信机制及异步编程场景。通过实例讲解如何高效处理大文件、构建数据流水线,并对比不同迭代方式的性能特点,助你编写低内存、高效率的Python代码。
96 0
|
10月前
|
安全 关系型数据库 测试技术
学习Python Web开发的安全测试需要具备哪些知识?
学习Python Web开发的安全测试需要具备哪些知识?
197 61
|
10月前
|
安全 测试技术 网络安全
如何在Python Web开发中进行安全测试?
如何在Python Web开发中进行安全测试?
|
3月前
|
测试技术 Python
Python测试报告生成:整合错误截图,重复用例执行策略,调整测试顺序及多断言机制。
如何组织这一切呢?你可以写一本名为“Python测试之道”的动作指南手册,或者创建一个包含测试策略、测试顺序、多断言机制的脚本库。只要你的测试剧本编写得足够独到,你的框架就会像一位执行任务的超级英雄,将任何潜伏于代码深处的错误无情地揪出来展现在光天化日之下。这些整理好的测试结果,不仅有利于团队协作,更像冒险故事中的精彩篇章,带给读者无尽的探索乐趣和深刻的思考。
102 10
|
4月前
|
数据可视化 Linux iOS开发
Python测量CPU和内存使用率
这些示例帮助您了解如何在Python中测量CPU和内存使用率。根据需要,可以进一步完善这些示例,例如可视化结果或限制程序在特定范围内的资源占用。
165 22
|
3月前
|
测试技术 Python
Python接口自动化测试中Mock服务的实施。
总结一下,Mock服务在接口自动化测试中的应用,可以让我们拥有更高的灵活度。而Python的 `unittest.mock`库为我们提供强大的支持。只要我们正确使用Mock服务,那么在任何情况下,无论是接口是否可用,都可以进行准确有效的测试。这样,就大大提高了自动化测试的稳定性和可靠性。
140 0
|
6月前
|
机器学习/深度学习 设计模式 测试技术
Python 高级编程与实战:构建自动化测试框架
本文深入探讨了Python中的自动化测试框架,包括unittest、pytest和nose2,并通过实战项目帮助读者掌握这些技术。文中详细介绍了各框架的基本用法和示例代码,助力开发者快速验证代码正确性,减少手动测试工作量。学习资源推荐包括Python官方文档及Real Python等网站。
|
6月前
|
存储 JSON API
Python测试淘宝店铺所有商品接口的详细指南
本文详细介绍如何使用Python测试淘宝店铺商品接口,涵盖环境搭建、API接入、签名生成、请求发送、数据解析与存储、异常处理等步骤。通过具体代码示例,帮助开发者轻松获取和分析淘宝店铺商品数据,适用于电商运营、市场分析等场景。遵守法规、注意调用频率限制及数据安全,确保应用的稳定性和合法性。
|
7月前
|
监控 Java 计算机视觉
Python图像处理中的内存泄漏问题:原因、检测与解决方案
在Python图像处理中,内存泄漏是常见问题,尤其在处理大图像时。本文探讨了内存泄漏的原因(如大图像数据、循环引用、外部库使用等),并介绍了检测工具(如memory_profiler、objgraph、tracemalloc)和解决方法(如显式释放资源、避免循环引用、选择良好内存管理的库)。通过具体代码示例,帮助开发者有效应对内存泄漏挑战。
320 1
|
10月前
|
监控 安全 测试技术
如何在实际项目中应用Python Web开发的安全测试知识?
如何在实际项目中应用Python Web开发的安全测试知识?
175 61

推荐镜像

更多