Skip to content

Instantly share code, notes, and snippets.

@freakynit
Created November 29, 2021 04:08
Show Gist options
  • Save freakynit/116363b6768c15c50c1d6ff8faee03d0 to your computer and use it in GitHub Desktop.
Save freakynit/116363b6768c15c50c1d6ff8faee03d0 to your computer and use it in GitHub Desktop.
Example usage of runtime.ReadMemStats function
package main
import (
"fmt"
"runtime"
"strconv"
"time"
)
func printMemStats(message string, rtm runtime.MemStats){
fmt.Println("\n===", message, "===")
fmt.Println("Mallocs: ", rtm.Mallocs)
fmt.Println("Frees: ", rtm.Frees)
fmt.Println("LiveObjects: ", rtm.Mallocs - rtm.Frees)
fmt.Println("PauseTotalNs: ", rtm.PauseTotalNs)
fmt.Println("NumGC: ", rtm.NumGC)
fmt.Println("LastGC: ", time.UnixMilli(int64(rtm.LastGC/1_000_000)))
fmt.Println("HeapObjects: ", rtm.HeapObjects)
fmt.Println("HeapAlloc: ", rtm.HeapAlloc)
}
func main() {
var rtm runtime.MemStats
runtime.ReadMemStats(&rtm)
printMemStats("Start", rtm)
a := make([]int64, 0)
var i int64
for i = 0 ; i < 10_000_000; i++ {
a = append(a, i)
}
runtime.ReadMemStats(&rtm)
printMemStats("After 10 million int64 appends", rtm)
var b []string
var j int
for j = 0 ; j < 10_000_000; j++ {
b = append(b, "hello"+strconv.Itoa(j))
}
runtime.ReadMemStats(&rtm)
printMemStats("After 10 million string appends", rtm)
runtime.GC()
runtime.ReadMemStats(&rtm)
printMemStats("After forced GC", rtm)
}
@aeon3k
Copy link

aeon3k commented Nov 6, 2023

thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment