From 48165d30b720091fca279a236ec100c90df5a96c Mon Sep 17 00:00:00 2001 From: Ivan Maidanski Date: Fri, 10 Jul 2015 00:29:43 +0300 Subject: [PATCH] Code refactoring, add test and document GC_get_memory_use * include/gc.h (GC_get_memory_use): Add comment. * include/gc.h (GC_get_memory_use): Decorate with GC_CALL; change return type from long to size_t. * misc.c (GC_get_memory_use): Likewise. * misc.c (get_size): Rename to block_add_size. * misc.c (get_size): Rename lptr parameter to pbytes; code refactoring. * misc.c (GC_get_memory_use): Rename "c" local variable to "bytes"; add DCL_LOCK_STATE. * tests/test.c (check_heap_stats): Call GC_get_memory_use (and print returned value). --- include/gc.h | 4 +++- misc.c | 21 ++++++++++----------- tests/test.c | 2 ++ 3 files changed, 15 insertions(+), 12 deletions(-) diff --git a/include/gc.h b/include/gc.h index 996586b2..ad5da167 100644 --- a/include/gc.h +++ b/include/gc.h @@ -724,7 +724,9 @@ GC_API size_t GC_CALL GC_get_prof_stats(struct GC_prof_stats_s *, size_t /* stats_sz */); #endif -GC_API long GC_get_memory_use(void); +/* Count total memory use in bytes by all allocated blocks. Acquires */ +/* the lock. */ +GC_API size_t GC_CALL GC_get_memory_use(void); /* Disable garbage collection. Even GC_gcollect calls will be */ /* ineffective. */ diff --git a/misc.c b/misc.c index 55d078c8..344d7b83 100644 --- a/misc.c +++ b/misc.c @@ -2014,23 +2014,22 @@ GC_API void * GC_CALL GC_do_blocking(GC_fn_type fn, void * client_data) } #endif /* !NO_DEBUGGING */ -static void get_size(struct hblk *h, word lptr) +static void block_add_size(struct hblk *h, word pbytes) { hdr *hhdr = HDR(h); - long bytes = WORDS_TO_BYTES(hhdr->hb_sz); - - bytes += HBLKSIZE-1; - bytes &= ~(HBLKSIZE-1); - - *(long *)lptr += bytes; + *(word *)pbytes += (WORDS_TO_BYTES(hhdr->hb_sz) + (HBLKSIZE - 1)) + & ~(HBLKSIZE - 1); } -long GC_get_memory_use() + +GC_API size_t GC_CALL GC_get_memory_use(void) { - long c = 0; + word bytes = 0; + DCL_LOCK_STATE; + LOCK(); - GC_apply_to_all_blocks(get_size, (word)&c); + GC_apply_to_all_blocks(block_add_size, (word)(&bytes)); UNLOCK(); - return c; + return (size_t)bytes; } /* Getter functions for the public Read-only variables. */ diff --git a/tests/test.c b/tests/test.c index 7d91d2dd..9607bddf 100644 --- a/tests/test.c +++ b/tests/test.c @@ -1519,6 +1519,8 @@ void check_heap_stats(void) # endif GC_printf("Total number of bytes allocated is %lu\n", (unsigned long)GC_get_total_bytes()); + GC_printf("Total memory use by allocated blocks is %lu bytes\n", + (unsigned long)GC_get_memory_use()); GC_printf("Final heap size is %lu bytes\n", (unsigned long)GC_get_heap_size()); if (GC_get_total_bytes() < n_tests * -- 2.40.0