0

PyPortal Memory
Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.

PyPortal Memory

by kwalkerk on Fri Jan 08, 2021 9:45 am

I'd like to be able see how much memory(ram) is available at different places in my program.

I can't find a way to print out available memory in CircuitPython.

Am I out of luck?

kwalkerk
 
Posts: 76
Joined: Wed Jan 11, 2017 11:54 am

Re: PyPortal Memory

by jerryn on Fri Jan 08, 2021 9:58 am

use:
Code: Select all | TOGGLE FULL SIZE
import gc
gc.mem_free()


Code: Select all | TOGGLE FULL SIZE
Press any key to enter the REPL. Use CTRL-D to reload.
Adafruit CircuitPython 6.0.1 on 2020-12-28; Adafruit PyPortal with samd51j20
>>> import gc
>>> gc.mem_free()
219984
>>>



jerryn
 
Posts: 1371
Joined: Sat Sep 14, 2013 9:05 am

Re: PyPortal Memory

by kwalkerk on Fri Jan 08, 2021 10:15 am

Thanks!

kwalkerk
 
Posts: 76
Joined: Wed Jan 11, 2017 11:54 am

Re: PyPortal Memory

by kevinjwalters on Fri Jan 08, 2021 4:02 pm

One thing to add here is that gc.mem_free() shows the amount of memory that's left free but there may be some objects which are no longer used but have not yet been garbage collected. It's common to run gc.collect() before retrieving the gc.mem_free() value to deal with this if you want to see all the free memory.

Here's an example:

Code: Select all | TOGGLE FULL SIZE
Adafruit CircuitPython 6.0.0 on 2020-11-16; Adafruit PyPortal with samd51j20
>>>
>>> import ulab
>>> import gc
>>> gc.mem_free()
220000
>>> big1 = ulab.zeros(20*1024, dtype=ulab.uint8)
>>> big2 = ulab.zeros(20*1024, dtype=ulab.uint8)
>>> big3 = ulab.zeros(20*1024, dtype=ulab.uint8)
>>> big4 = ulab.zeros(20*1024, dtype=ulab.uint8)
>>> gc.mem_free()
136896
>>> del big1, big3
>>> gc.mem_free()
136704
>>> gc.collect()
>>> gc.mem_free()
178544


That example alludes to another issue with memory, big1 and big3 are likely to be sandwiched between start of memory, big2 and big4. The GC does not compact those gaps which can lead to situations where an allocation typically for a large object can fail because there's not a single, big, free lump available for it.

kevinjwalters
 
Posts: 836
Joined: Sun Oct 01, 2017 3:15 pm

Re: PyPortal Memory

by kwalkerk on Fri Jan 08, 2021 4:09 pm

Thank you

kwalkerk
 
Posts: 76
Joined: Wed Jan 11, 2017 11:54 am

Please be positive and constructive with your questions and comments.