How to limit the maximum memory your Python program can use
This article mainly explains "how to limit the maximum memory that your Python program can use". The explanation in the article is simple and clear, and easy to learn and understand. Please follow the editor's train of thought to study and learn "how to limit the maximum memory that your Python program can use"!
To limit the maximum memory that Python programs can use, we can use the resource module that comes with Python.
First, obtain the default memory soft upper limit and hard upper limit of the system:
Import resource soft, hard = resource.getrlimit (resource.RLIMIT_AS)
The resource.RLIMIT_AS is actually the number 5, which represents memory resources. The soft limit is an adjustable upper limit of memory usage, and hard is an upper limit of memory usage that is difficult to adjust dynamically once set.
The effect of running on my computer is as follows:
At first, the values of soft and hard are the same. And their units are not bits. It's a unit smaller than a bit. My computer has 8GB memory, and 8 * 1024 ^ 6 is exactly equal to the values of hard and soft here.
Next, set the maximum memory that can be used by the currently running Python program:
Resource.setrlimit (resource.RLIMIT_AS, (maximum limit, hard))
The maximum upper limit is an integer. Suppose I want to limit the maximum amount of memory that the current program can use 500MB, then the maximum limit can be set to:
1024 ^ 6 = 576460752303423488
So it is set to:
Resource.setrlimit (resource.RLIMIT_AS, (576460752303423488, hard))
Then when the current Python program uses more memory than 500MB, the program will throw MemoryError.
Thank you for reading, the above is the content of "how to limit the maximum memory that your Python program can use". After the study of this article, I believe you have a deeper understanding of how to limit the maximum memory that your Python program can use. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!