diff --git a/malloc_heap.go b/malloc_heap.go index 810d460..cb0c0e2 100644 --- a/malloc_heap.go +++ b/malloc_heap.go @@ -10,3 +10,19 @@ func getChunk() []byte { func putChunk(chunk []byte) { // No-op. } + +// GetOffHeapMemoryStats returns the memory allocation statistics from off-heap +// memory. This function returns two numbers: +// +// - The first number represents the total memory allocated from the off-heap, +// including both used and free memory. +// +// - The second number represents the memory size which is allocated from +// the off-heap but currently not in use (free memory). +// +// Note that these statistics provide insights into the off-heap memory usage, +// which is memory managed directly by the application and not subject to golang +// garbage collection. +func GetOffHeapMemoryStats() (uint64, uint64) { + return 0, 0 +} diff --git a/malloc_mmap.go b/malloc_mmap.go index e24d578..c7a055a 100644 --- a/malloc_mmap.go +++ b/malloc_mmap.go @@ -16,6 +16,10 @@ const chunksPerAlloc = 1024 var ( freeChunks []*[chunkSize]byte freeChunksLock sync.Mutex + + // Statistics of memory allocated via off-heap, guarded by lock. + allocatedSize uint64 // The total memory size allocated from the offheap + freeChunkSize uint64 // The total memory size allocated but not used ) func getChunk() []byte { @@ -31,12 +35,15 @@ func getChunk() []byte { p := (*[chunkSize]byte)(unsafe.Pointer(&data[0])) freeChunks = append(freeChunks, p) data = data[chunkSize:] + allocatedSize += chunkSize + freeChunkSize += chunkSize } } n := len(freeChunks) - 1 p := freeChunks[n] freeChunks[n] = nil freeChunks = freeChunks[:n] + freeChunkSize -= chunkSize freeChunksLock.Unlock() return p[:] } @@ -50,5 +57,25 @@ func putChunk(chunk []byte) { freeChunksLock.Lock() freeChunks = append(freeChunks, p) + freeChunkSize += chunkSize freeChunksLock.Unlock() } + +// GetOffHeapMemoryStats returns the memory allocation statistics from off-heap +// memory. This function returns two numbers: +// +// - The first number represents the total memory allocated from the off-heap, +// including both used and free memory. +// +// - The second number represents the memory size which is allocated from +// the off-heap but currently not in use (free memory). +// +// Note that these statistics provide insights into the off-heap memory usage, +// which is memory managed directly by the application and not subject to golang +// garbage collection. +func GetOffHeapMemoryStats() (uint64, uint64) { + freeChunksLock.Lock() + defer freeChunksLock.Unlock() + + return allocatedSize, freeChunkSize +}