是否有 Python 方法来计算 space 复杂度?

Is there a Python method to calculate 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

通过画图time_n vs input_n,我们可以观察时间复杂度是常量、线性、指数等

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

您可以将 memory_profiler 与这样的装饰器一起使用:

from memory_profiler import profile

  @profile(precision=4)
  def func():
     your function

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

更新: 感谢@hunzter,您可以找到文档 here.