通过比较运行算法所需的时间与输入的大小,计算 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
与input_n
的图表,我们可以观察时间复杂度是否为常数、线性、指数等。
是否有一种类似的经验性编程方法来计算 Python 中算法的空间复杂度,我们可以测量随着输入大小的增长所使用的空间量?
最佳答案
您可以将 memory_profiler
与装饰器一起使用,如下所示:
from memory_profiler import profile
@profile(precision=4)
def func():
your function
memory_profiler
中还有另一个名为 mprof
的函数,它也很有用。如果您想查看内存是否定期清理和释放,这会很有用。只需在您选择的 shell 中运行 mprof run script script_args 即可。 mprof 将自动创建脚本随时间的内存使用情况的图表,您可以通过运行 mprofplot 来查看该图表。但它需要matplotlib
。
更新: 感谢@hunzter,您可以找到文档 here .
关于python - Python有计算空间复杂度的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59114941/