Skip to content

Commit 02de0c5

Browse files
committed
Add new alloc metric: current_bytes_allocated.
Unlike total_bytes_allocated, this tracks m_free()'s too.
1 parent 43f1c80 commit 02de0c5

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

py/malloc.c

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
#include "misc.h"
55

66
static int total_bytes_allocated = 0;
7+
static int current_bytes_allocated = 0;
78

89
void *m_malloc(int num_bytes) {
910
if (num_bytes == 0) {
@@ -15,6 +16,7 @@ void *m_malloc(int num_bytes) {
1516
return NULL;
1617
}
1718
total_bytes_allocated += num_bytes;
19+
current_bytes_allocated += num_bytes;
1820
return ptr;
1921
}
2022

@@ -28,6 +30,7 @@ void *m_malloc0(int num_bytes) {
2830
return NULL;
2931
}
3032
total_bytes_allocated += num_bytes;
33+
current_bytes_allocated += num_bytes;
3134
return ptr;
3235
}
3336

@@ -46,16 +49,23 @@ void *m_realloc(void *ptr, int old_num_bytes, int new_num_bytes) {
4649
// shrunk to 1K and then grown to 2K again. It's still 2K
4750
// allocated total. If we process only positive increments,
4851
// we'll count 3K.
49-
total_bytes_allocated += new_num_bytes - old_num_bytes;
52+
int diff = new_num_bytes - old_num_bytes;
53+
total_bytes_allocated += diff;
54+
current_bytes_allocated += diff;
5055
return ptr;
5156
}
5257

5358
void m_free(void *ptr, int num_bytes) {
5459
if (ptr != NULL) {
5560
free(ptr);
5661
}
62+
current_bytes_allocated -= num_bytes;
5763
}
5864

5965
int m_get_total_bytes_allocated(void) {
6066
return total_bytes_allocated;
6167
}
68+
69+
int m_get_current_bytes_allocated(void) {
70+
return current_bytes_allocated;
71+
}

py/misc.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ void *m_realloc(void *ptr, int old_num_bytes, int new_num_bytes);
3232
void m_free(void *ptr, int num_bytes);
3333

3434
int m_get_total_bytes_allocated(void);
35+
int m_get_current_bytes_allocated(void);
3536

3637
/** unichar / UTF-8 *********************************************/
3738

0 commit comments

Comments
 (0)