Issue
In my deployment environment I am trying to run a script with a loop similar to the one below. However, the script get killed because it eats too much memory. When I checked the loop for memory consumption, I noticed that on each iteration of the loop the consumption grows by 1-2MB.
Can someone advise what is the reason for such growing consumption and how can I prevent it?
import tracemalloc
from mongoengine_models import SomeModel
tracemalloc.start()
for count, rel in enumerate(SomeModel.objects.filter(some_attr="some_value")):
current, peak = tracemalloc.get_traced_memory()
current_mb = current / 10**6
peak_mb = peak / 10**6
print(f"Current memory usage is {current_mb}MB; Peak was {peak_mb}MB")
print(count, rel.some_other_attr_1, rel.some_other_attr_2)
tracemalloc.stop()
UPDATE: I figured out I can prevent the growing consumption by doing del rel, del some_other_attr_1, del some_other_attr_2 at the end of each iteration, by it feels like a hacky solution.
Solution
The results from the queryset are cached. You can avoid this by using no_cache()
SomeModel.objects.no_cache().filter(some_attr="some_value")
There is a post about no_cache here.
Answered By - Jonas Ekström Answer Checked By - Cary Denson (Python.Easybugfix Admin)
Post a Comment
Post a Comment