Created
November 29, 2021 04:08
-
-
Save freakynit/116363b6768c15c50c1d6ff8faee03d0 to your computer and use it in GitHub Desktop.
Example usage of runtime.ReadMemStats function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks