Is there a way for a Python program to determine how much memory it's currently using? I've seen discussions about memory usage for a single object, but what I need is total memory usage for the process, so that I can determine when it's necessary to start discarding cached data.
Here is a useful solution that works for various operating systems, including Linux, Windows, etc.:
import psutil
process = psutil.Process()
print(process.memory_info().rss) # in bytes
Notes:
do pip install psutil
if it is not installed yet
handy one-liner if you quickly want to know how many MiB your process takes:
import os, psutil; print(psutil.Process(os.getpid()).memory_info().rss / 1024 ** 2)
with Python 2.7 and psutil 5.6.3, it was process.memory_info()[0]
instead (there was a change in the API later).