22#include <stdlib.h>
33
44#include "misc.h"
5+ #include "mpconfig.h"
6+ #include "defaultconfig.h"
57
8+ #if MICROPY_MEM_STATS
69static int total_bytes_allocated = 0 ;
710static int current_bytes_allocated = 0 ;
811static int peak_bytes_allocated = 0 ;
912
1013#define UPDATE_PEAK () { if (current_bytes_allocated > peak_bytes_allocated) peak_bytes_allocated = current_bytes_allocated; }
14+ #endif
1115
1216void * m_malloc (int num_bytes ) {
1317 if (num_bytes == 0 ) {
@@ -18,9 +22,11 @@ void *m_malloc(int num_bytes) {
1822 printf ("could not allocate memory, allocating %d bytes\n" , num_bytes );
1923 return NULL ;
2024 }
25+ #if MICROPY_MEM_STATS
2126 total_bytes_allocated += num_bytes ;
2227 current_bytes_allocated += num_bytes ;
2328 UPDATE_PEAK ();
29+ #endif
2430 return ptr ;
2531}
2632
@@ -33,9 +39,11 @@ void *m_malloc0(int num_bytes) {
3339 printf ("could not allocate memory, allocating %d bytes\n" , num_bytes );
3440 return NULL ;
3541 }
42+ #if MICROPY_MEM_STATS
3643 total_bytes_allocated += num_bytes ;
3744 current_bytes_allocated += num_bytes ;
3845 UPDATE_PEAK ();
46+ #endif
3947 return ptr ;
4048}
4149
@@ -49,6 +57,7 @@ void *m_realloc(void *ptr, int old_num_bytes, int new_num_bytes) {
4957 printf ("could not allocate memory, reallocating %d bytes\n" , new_num_bytes );
5058 return NULL ;
5159 }
60+ #if MICROPY_MEM_STATS
5261 // At first thought, "Total bytes allocated" should only grow,
5362 // after all, it's *total*. But consider for example 2K block
5463 // shrunk to 1K and then grown to 2K again. It's still 2K
@@ -58,24 +67,39 @@ void *m_realloc(void *ptr, int old_num_bytes, int new_num_bytes) {
5867 total_bytes_allocated += diff ;
5968 current_bytes_allocated += diff ;
6069 UPDATE_PEAK ();
70+ #endif
6171 return ptr ;
6272}
6373
6474void m_free (void * ptr , int num_bytes ) {
6575 if (ptr != NULL ) {
6676 free (ptr );
6777 }
78+ #if MICROPY_MEM_STATS
6879 current_bytes_allocated -= num_bytes ;
80+ #endif
6981}
7082
7183int m_get_total_bytes_allocated (void ) {
84+ #if MICROPY_MEM_STATS
7285 return total_bytes_allocated ;
86+ #else
87+ return -1 ;
88+ #endif
7389}
7490
7591int m_get_current_bytes_allocated (void ) {
92+ #if MICROPY_MEM_STATS
7693 return current_bytes_allocated ;
94+ #else
95+ return -1 ;
96+ #endif
7797}
7898
7999int m_get_peak_bytes_allocated (void ) {
100+ #if MICROPY_MEM_STATS
80101 return peak_bytes_allocated ;
102+ #else
103+ return -1 ;
104+ #endif
81105}
0 commit comments