From 5008515b0379d9d23db6d1d37fa4d2433c1731ba Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Wed, 3 May 2023 14:33:52 -0300 Subject: [PATCH] builtin: heap memory usage api (#18103) --- vlib/builtin/builtin.c.v | 30 +++++++++++++++++++++++++++ vlib/builtin/builtin_d_gcboehm.c.v | 3 +++ vlib/builtin/builtin_notd_gcboehm.c.v | 4 ++++ 3 files changed, 37 insertions(+) diff --git a/vlib/builtin/builtin.c.v b/vlib/builtin/builtin.c.v index 3aca604374..a36719b97d 100644 --- a/vlib/builtin/builtin.c.v +++ b/vlib/builtin/builtin.c.v @@ -643,6 +643,36 @@ pub fn memdup_uncollectable(src voidptr, sz int) voidptr { } } +pub struct GCHeapUsage { +pub: + heap_size usize + free_bytes usize + total_bytes usize + unmapped_bytes usize + bytes_since_gc usize +} + +// gc_heap_usage returns the info about heap usage +pub fn gc_heap_usage() GCHeapUsage { + $if gcboehm ? { + mut res := GCHeapUsage{} + C.GC_get_heap_usage_safe(&res.heap_size, &res.free_bytes, &res.unmapped_bytes, + &res.bytes_since_gc, &res.total_bytes) + return res + } $else { + return GCHeapUsage{} + } +} + +// gc_memory_use returns the total memory use in bytes by all allocated blocks +pub fn gc_memory_use() usize { + $if gcboehm ? { + return C.GC_get_memory_use() + } $else { + return 0 + } +} + [inline] fn v_fixed_index(i int, len int) int { $if !no_bounds_checking { diff --git a/vlib/builtin/builtin_d_gcboehm.c.v b/vlib/builtin/builtin_d_gcboehm.c.v index 0a13b642ee..564c0ad0d7 100644 --- a/vlib/builtin/builtin_d_gcboehm.c.v +++ b/vlib/builtin/builtin_d_gcboehm.c.v @@ -132,3 +132,6 @@ pub fn gc_check_leaks() { C.GC_gcollect() } } + +fn C.GC_get_heap_usage_safe(pheap_size &usize, pfree_bytes &usize, punmapped_bytes &usize, pbytes_since_gc &usize, ptotal_bytes &usize) +fn C.GC_get_memory_use() usize diff --git a/vlib/builtin/builtin_notd_gcboehm.c.v b/vlib/builtin/builtin_notd_gcboehm.c.v index 71ee1aaa79..56002ff54a 100644 --- a/vlib/builtin/builtin_notd_gcboehm.c.v +++ b/vlib/builtin/builtin_notd_gcboehm.c.v @@ -14,6 +14,10 @@ fn C.GC_REALLOC(ptr voidptr, n usize) voidptr fn C.GC_FREE(ptr voidptr) +fn C.GC_get_heap_usage_safe(pheap_size &usize, pfree_bytes &usize, punmapped_bytes &usize, pbytes_since_gc &usize, ptotal_bytes &usize) + +fn C.GC_get_memory_use() usize + // provide an empty function when manual memory management is used // to simplify leak detection //