是否有计算空间复杂度的 Python 方法?

Fat*_*ici 4 python complexity-theory time-complexity space-complexity

通过比较运行算法所需的时间与输入的大小,在 Python 中计算时间复杂度非常容易。我们可以这样做:

import time

start = time.time()
<Run the algorithm on input_n (input of size n)>
end = time.time()
time_n = end - start
Run Code Online (Sandbox Code Playgroud)

通过绘制time_nvs input_n,我们可以观察时间复杂度是否为常数、线性、指数等。

是否有类似的经验性编程方法来计算 Python 中算法的空间复杂度,我们可以在其中测量随着输入大小的增长而使用的空间量?

prh*_*mma 9

你可以使用这样memory_profiler的装饰器:

from memory_profiler import profile

  @profile(precision=4)
  def func():
     your function
Run Code Online (Sandbox Code Playgroud)

还有所谓的另一个函数mprofmemory_profiler,这将是有用的。如果您想查看您的内存是否被定期清理和释放,这会很有用。只需在您选择的 shell 中运行 mprof run script script_args 即可。mprof 将自动创建脚本内存使用情况随时间变化的图表,您可以通过运行 mprof plot 查看该图表。matplotlib虽然它需要。

更新:感谢@hunzter,您可以在这里找到文档。