Go-标准库-runtime(二)

2023-04-23 07:37:28 浏览数 (1)

内存分配

runtime包中的内存分配函数可以动态地分配和释放内存,如下所示:

代码语言:javascript复制
package main

import (
	"fmt"
	"runtime"
)

func main() {
	var mem runtime.MemStats
	runtime.ReadMemStats(&mem)
	fmt.Println("Before allocation:")
	fmt.Printf("Alloc = %v MiBn", mem.Alloc/1024/1024)
	fmt.Printf("TotalAlloc = %v MiBn", mem.TotalAlloc/1024/1024)
	fmt.Printf("HeapAlloc = %v MiBn", mem.HeapAlloc/1024/1024)
	fmt.Printf("HeapSys = %v MiBn", mem.HeapSys/1024/1024)

	data := make([]byte, 1024*1024*1024)
	fmt.Println("After allocation:")
	runtime.ReadMemStats(&mem)
	fmt.Printf("Alloc = %v MiBn", mem.Alloc/1024/1024)
	fmt.Printf("TotalAlloc = %v MiBn", mem.TotalAlloc/1024/1024)
	fmt.Printf("HeapAlloc = %v MiBn", mem.HeapAlloc/1024/1024)
	fmt.Printf("HeapSys = %v MiBn", mem.HeapSys/1024/1024)

	data = nil
	runtime.GC()
	fmt.Println("After GC:")
	runtime.ReadMemStats(&mem)
	fmt.Printf("Alloc = %v MiBn", mem.Alloc/1024/1024)
	fmt.Printf("TotalAlloc = %v MiBn", mem.TotalAlloc/1024/1024)
	fmt.Printf("HeapAlloc = %v MiBn", mem.HeapAlloc/1024/1024)
	fmt.Printf("HeapSys = %v MiBn", mem.HeapSys/1024/1024)
}

上面的代码先打印出内存分配前的内存信息,然后分配1GB的内存,再次打印出内存分配后的内存信息,然后将分配的内存置为nil,触发垃圾回收,最后再次打印出内存回收后的内存信息。

go

0 人点赞