Repository navigation
How can I reduce memory consumption when processing millions of records in Python? #15740
Replies: 4 comments
|
let's keep in touch via discord |
|
Hard to be specific without knowing the data format or what you're computing.... don't load all the records at once (stream them with a generator or read in chunks), and keep only small running results in memory. with open("data.txt") as f:
total = sum(len(line) for line in f) # one line in memory at a timememory then stays flat no matter how many records there are, see: https://docs.python.org/3/howto/functional.html#generators |
|
A useful approach is to avoid loading all records into memory at once. The best technique depends on the data format and what you’re calculating. For a large CSV file, you can process it in chunks with pandas: import pandas as pd This keeps only one chunk in memory at a time. You can also specify smaller data types with dtype when you know the range of your values, which can reduce memory usage further. A few other tips:
The key is to process data incrementally and keep only the intermediate results you actually need. |
On Python 3.12+ you can use itertools.batched instead.
|
Uh oh!
There was an error while loading. Please reload this page.
?what is your answer?
All reactions