ReadMemstats

通过 runtime.ReadMemStats() 查看内存
package main

import (
    "log"
    "runtime"
    "time"
)

func readMemStats() {

    var ms runtime.MemStats

    runtime.ReadMemStats(&ms)

    log.Printf(" ===> Alloc:%d(bytes) HeapIdle:%d(bytes) HeapReleased:%d(bytes)", ms.Alloc, ms.HeapIdle, ms.HeapReleased)
}

func test() {
    //slice 会动态扩容,用slice来做堆内存申请
    container := make([]int, 8)

    log.Println(" ===> loop begin.")
    for i := 0; i < 32*1000*1000; i++ {
        container = append(container, i)
        if ( i == 16*1000*1000) {
            readMemStats()
        }
    }

    log.Println(" ===> loop end.")
}

func main() {
    log.Println(" ===> [Start].")

    readMemStats()
    test()
    readMemStats()

    log.Println(" ===> [force gc].")
    runtime.GC() //强制调用gc回收

    log.Println(" ===> [Done].")
    readMemStats()

    go func() {
        for {
            readMemStats()
            time.Sleep(10 * time.Second)
        }
    }()

    time.Sleep(3600 * time.Second) //睡眠,保持程序不退出
}
go run memstate/main.go 
2021/04/01 22:14:48  ===> [Start].
2021/04/01 22:14:48  ===> Alloc:128432(bytes) HeapIdle:66379776(bytes) HeapReleased:66347008(bytes)
2021/04/01 22:14:48  ===> loop begin.
2021/04/01 22:14:48  ===> Alloc:323365824(bytes) HeapIdle:145661952(bytes) HeapReleased:71827456(bytes)
2021/04/01 22:14:49  ===> loop end.
2021/04/01 22:14:49  ===> Alloc:631492800(bytes) HeapIdle:307290112(bytes) HeapReleased:117186560(bytes)
2021/04/01 22:14:49  ===> [force gc].
2021/04/01 22:14:49  ===> [Done].
2021/04/01 22:14:49  ===> Alloc:128552(bytes) HeapIdle:938655744(bytes) HeapReleased:117121024(bytes)
2021/04/01 22:14:49  ===> Alloc:129368(bytes) HeapIdle:938655744(bytes) HeapReleased:117121024(bytes)
2021/04/01 22:14:59  ===> Alloc:129592(bytes) HeapIdle:938655744(bytes) HeapReleased:117121024(bytes)
2021/04/01 22:15:09  ===> Alloc:130184(bytes) HeapIdle:938655744(bytes) HeapReleased:158097408(bytes)

可看到Alloc下降,表示内存已经被GC回收。