我有一个 python 程序,它有时会消耗大量 RAM。 我试图通过
限制使用 resource.setrlimit(resource.RLIMIT_AS, (2**32, 2**32))
但是,这会导致 Python 崩溃而不是引发 MemoryError。
如何让 Python 保持活力? IE。我想要 MemoryError。
当我尝试在 cvxpy 中求解大型实例时,问题出现了。 (这也意味着我无法减少代码的内存使用量 - 它不是我的代码。) 但是当我通过
分配大量 RAM 时- numpy (
numpy.arange(1000*1000*250, dtype="u8"),
来自 How do I use `setrlimit` to limit memory usage? RLIMIT_AS kills too soon; RLIMIT_DATA, RLIMIT_RSS, RLIMIT_STACK kill not at all ), 或 - shell (call
yes | tr\\n x | head -c $((1024*1024*1024*10)) | grep n,
来自 https://unix.stackexchange.com/questions/99334/how-to-fill-90-of-the-free-memory )
然后我得到了预期的MemoryError。
有什么区别?
编辑:错误信息是:
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
编辑:我现在有一个 (M)WE。
import cvxpy as cvx
import numpy as np
import random
import resource
resource.setrlimit(resource.RLIMIT_AS, (2**32, 2**32))
# Problem data.
m = 500
n = 500
np.random.seed(1)
random.seed(1)
A = np.random.randn(m, n)
b = np.random.randn(m, 1)
# Construct the problem.
X = cvx.Semidef(m)
objective = cvx.Minimize(cvx.sum_entries(cvx.norm(X)))
constraints = [sum([X[random.randint(0,499),random.randint(0,499)] for _ in range(50)]) >= random.random() for _ in range(5000)]
prob = cvx.Problem(objective, constraints)
print("Optimal value", prob.solve(solver = 'SCS'))
几秒钟后,它开始占用大量内存(超过 1GB,这应该是限制),然后因上述错误而崩溃。
请您参考如下方法:
如果 Python 可以在错误实际发生之前确定错误将要发生,Python 只会抛出 MemoryError。否则,它会崩溃。查看MemoryError的官方描述:
https://docs.python.org/2/library/exceptions.html#exceptions.MemoryError
