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

x33g5p2x  于2021-10-04 转载在 Python  
字(5.0k)|赞(0)|评价(0)|浏览(304)

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

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

相关文章