Heap Usage

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
Loxy618
Posts: 21
Joined: Wed Apr 24, 2019 2:01 am

Heap Usage

Post by Loxy618 » Thu Jan 16, 2020 10:47 pm

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.

stijn
Posts: 735
Joined: Thu Apr 24, 2014 9:13 am

Re: Heap Usage

Post by stijn » Fri Jan 17, 2020 9:20 am

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
 

Post Reply