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)
}
@freakynit
Copy link
Author

Output

=== Start ===
Mallocs:  228
Frees:  3
LiveObjects:  225
PauseTotalNs:  0
NumGC:  0
LastGC:  1970-01-01 05:30:00 +0530 IST
HeapObjects:  225
HeapAlloc:  137320

=== After 10 million int64 appends ===
Mallocs:  341
Frees:  104
LiveObjects:  237
PauseTotalNs:  557209
NumGC:  17
LastGC:  2021-11-29 09:36:08.33 +0530 IST
HeapObjects:  237
HeapAlloc:  152735680

=== After 10 million string appends ===
Mallocs:  20000307
Frees:  8709822
LiveObjects:  11290485
PauseTotalNs:  933867
NumGC:  23
LastGC:  2021-11-29 09:36:09.316 +0530 IST
HeapObjects:  11290485
HeapAlloc:  478861336

=== After forced GC ===
Mallocs:  20000321
Frees:  20000076
LiveObjects:  245
PauseTotalNs:  1018576
NumGC:  24
LastGC:  2021-11-29 09:36:09.532 +0530 IST
HeapObjects:  245
HeapAlloc:  136448

@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