程序笔记   发布时间:2022-07-09  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Python 关于运行时间、调用次数及内存使用的性能测试❤️大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

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

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

一、 Module time

time.time

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

>>> 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
>>> 

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

除time()函数外࿰c;时间库里可用来计时的函数有很多࿰c;还成对的(_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 表示的是从程序的启动时间开始按秒计算的偏移量࿰c;如下面所举的例子中࿰c;它的返回值(613.323613)表示Python IDLE SHell窗口打开的时间。

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

>>> 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࿰c;上例中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

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

>>> 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࿰c;因为我用傻办法验证过所以我知道。

这个模块还能在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

运行时间逐行分析报告࿰c;测试文件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导入࿰c;只在测试函数前加上装饰器 @profile ࿰c;测试在DOS窗口进行:

D:>kernprof -l -v test1.py 832040 Wrote profile results to test1.py.lprof Timer unit: 1e-06 s

@R_720_10586@l 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 @H_45_35@memory_profiler

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

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࿰c;所以没装没能亲测࿰c;大致用法:

    from guppy import hpy
    import gc

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

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

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

D:>pip install xxModule

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

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

大佬总结

以上是大佬教程为你收集整理的Python 关于运行时间、调用次数及内存使用的性能测试❤️全部内容,希望文章能够帮你解决Python 关于运行时间、调用次数及内存使用的性能测试❤️所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。