Page 1 of 1

Heap Usage

Posted: Thu Jan 16, 2020 10:47 pm
by Loxy618
Hello, currently I allocated python to use a 32K array as a the heap. I am trying to stress test the heap and want to understand how/when its used, how I can write scripts to cause it to get fully used so I can properly handle any exceptions.

Re: Heap Usage

Posted: Fri Jan 17, 2020 9:20 am
by stijn
There's a bunch of functions in the micropython modules showing memory usage:

Code: Select all

>>> import micropython
>>> dir(micropython)
['__class__', '__name__', 'const', 'heap_lock', 'heap_unlock', 'kbd_intr', 'mem_current', 'mem_info', 'mem_peak', 'mem_total', 'opt_level', 'pystack_use', 'qstr_info', 'stack_use']
>>>  micropython.mem_info()
mem: total=12804, current=3232, peak=4819
stack: 11872
GC: total: 2072832, used: 3936, free: 2068896
Getting the heap fully used isn't too hard: just allocate a lot of memory using list/array/string or so:

Code: Select all

>>> a = [1.0] * 100000                                                  
>>> a = [1.0] * 10000000                                                
Traceback (most recent call last):                                      
  File "<stdin>", line 1, in <module>                                   
MemoryError: memory allocation failed, allocating 80000000 bytes        
>>> micropython.mem_info()                                              
mem: total=824033, current=804929, peak=806516                          
stack: 11872                                                            
GC: total: 2072832, used: 804416, free: 1268416                         
 No. of 1-blocks: 60, 2-blocks: 5, max blk sz: 25000, max free sz: 39584
>>> b = [1.0] * 100000                                                  
>>> micropython.mem_info()                                              
mem: total=1628281, current=1605281, peak=1606868                       
stack: 11872                                                            
GC: total: 2072832, used: 1604864, free: 467968                         
 No. of 1-blocks: 73, 2-blocks: 4, max blk sz: 25000, max free sz: 14584