aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/examples/memstats/memstats.go
blob: f0224ac0ffe82fbd797e641208e59e31ead66b79 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package main

import (
	"math/rand"
	"runtime"
	"time"
)

func main() {

	ms := runtime.MemStats{}

	for {
		escapesToHeap()
		runtime.ReadMemStats(&ms)
		println("Heap before GC. Used: ", ms.HeapInuse, " Free: ", ms.HeapIdle, " Meta: ", ms.GCSys)
		runtime.GC()
		runtime.ReadMemStats(&ms)
		println("Heap after  GC. Used: ", ms.HeapInuse, " Free: ", ms.HeapIdle, " Meta: ", ms.GCSys)
		time.Sleep(5 * time.Second)
	}

}

func escapesToHeap() {
	n := rand.Intn(100)
	println("Doing ", n, " iterations")
	for i := 0; i < n; i++ {
		s := make([]byte, i)
		_ = append(s, 42)
	}
}