// go 1.18
// 가비지 콜렉션 확인
package study
import (
"fmt"
"math/rand"
"runtime"
"time"
)
func SliceGC() {
checkGC(sliceGC)
}
func sliceGC() {
intArr := make([]int, 900000)
for i := 0; i < len(intArr); i++ {
intArr[i] = rand.Int()
}
}
func checkGC(funcToCheck func()) {
var ms runtime.MemStats
printMemStat(ms)
funcToCheck()
printMemStat(ms)
}
func printMemStat(ms runtime.MemStats) {
runtime.ReadMemStats(&ms)
fmt.Println("--------------------------------------")
fmt.Println("Memory Statistics Reporting time: ", time.Now())
fmt.Println("--------------------------------------")
fmt.Println("Bytes of allocated heap objects: ", ms.Alloc)
fmt.Println("Total bytes of Heap object: ", ms.TotalAlloc)
fmt.Println("Bytes of memory obtained from OS: ", ms.Sys)
fmt.Println("Count of heap objects: ", ms.Mallocs)
fmt.Println("Count of heap objects freed: ", ms.Frees)
fmt.Println("Count of live heap objects", ms.Mallocs-ms.Frees)
fmt.Println("Number of completed GC cycles: ", ms.NumGC)
fmt.Println("--------------------------------------")
}
프로세스에 할당된 메모리에 근접하자, 가비지 콜렉션이 발생하여 "live heap objects"가 일정하게 유지됨
--------------------------------------
Memory Statistics Reporting time: 2022-08-14 01:07:35.127442 +0900 KST m=+0.000554668
--------------------------------------
Bytes of allocated heap objects: 121720
Total bytes of Heap object: 121720
Bytes of memory obtained from OS: 8522768
Count of heap objects: 152
Count of heap objects freed: 2
Count of live heap objects 150
Number of completed GC cycles: 0
--------------------------------------
--------------------------------------
Memory Statistics Reporting time: 2022-08-14 01:07:35.163681 +0900 KST m=+0.036791709
--------------------------------------
Bytes of allocated heap objects: 7317080
Total bytes of Heap object: 7331432
Bytes of memory obtained from OS: 17500944
Count of heap objects: 200
Count of heap objects freed: 51
Count of live heap objects 149
Number of completed GC cycles: 1
--------------------------------------