To retrieve memory statistics such as allocated memory using runtime.ReadMemStats()
, follow these steps:
runtime
package at the beginning of your code:import "runtime"
runtime.MemStats
struct, which is predefined in the runtime
package, should be used for this purpose:var memStats runtime.MemStats
runtime.ReadMemStats()
function to populate the memStats
struct with the current memory statistics:runtime.ReadMemStats(&memStats)
memStats
struct. For example, to retrieve the total allocated memory, you can access the Alloc
field of the memStats
struct:allocatedMemory := memStats.Alloc
Here's an example program that retrieves the allocated memory and prints it:
package main
import (
"fmt"
"runtime"
)
func main() {
var memStats runtime.MemStats
// Retrieve memory statistics
runtime.ReadMemStats(&memStats)
// Access allocated memory
allocatedMemory := memStats.Alloc
fmt.Printf("Allocated memory: %d bytes\n", allocatedMemory)
}
By running this program, you will get the current allocated memory in bytes.