Skip to content

Instantly share code, notes, and snippets.

@ifq
Last active December 20, 2015 20:39
Show Gist options
  • Save ifq/6191684 to your computer and use it in GitHub Desktop.
Save ifq/6191684 to your computer and use it in GitHub Desktop.
测试下一个基本的结构体在Golang下的内存消耗情况
package main
// 为一个小项目做准备,测试下数据结构的内存消耗情况
// 初次接触Go语言,很多东西需要了解
// 下面的结构体,创建1,000,000各 imgobj 时的log:
// 2013/08/09 14:53:42 alloc:307904, heapAlloc:307904
// 2013/08/09 14:53:42 alloc:7469888, heapAlloc:7469888
// 2013/08/09 14:53:42 alloc:12406664, heapAlloc:12406664
// 2013/08/09 14:53:43 alloc:26354224, heapAlloc:26354224
// 2013/08/09 14:53:43 alloc:24996016, heapAlloc:24996016
// 2013/08/09 14:53:43 alloc:36320616, heapAlloc:36320616
// 2013/08/09 14:53:44 alloc:55647632, heapAlloc:55647632
// 2013/08/09 14:53:44 alloc:62823392, heapAlloc:62823392
// 2013/08/09 14:53:44 alloc:55843616, heapAlloc:55843616
// 2013/08/09 14:53:45 alloc:72695264, heapAlloc:72695264
// 2013/08/09 14:53:45 alloc:81131208, heapAlloc:81131208
// 2013/08/09 14:53:45 time : 3.128207177s
//
// 一开始实验创建 50000 个 dir,每个存储 1-50000各 imgobj(递增),out of mem.
// 以为是程序问题,结果算了下确实内存不够。。。
//
// [2013-08-14 三] https://code.google.com/p/go/issues/detail?id=909
// 原来 out of mem 错误不是正常现象,而是Go在32bit系统上 的 GC 的缺陷。。
import (
"time"
"strconv"
"log"
"runtime"
"strings"
)
var (
dirs Imageset
)
// 待测试的数据结构
type Imageset map[string]imgdir
type imgdir struct {
imgs []imgobj
}
type imgobj struct {
path string
size int
time time.Time
tags []string
location string
}
func init() {
dirs = make(Imageset)
}
func main() {
start := time.Now()
// 创建的dir对象个数
for i := 0; i < 1000; i++ {
// 创建的imgobj个数
imgs1 := make([]imgobj, 1000)
for _, c := range imgs1 {
c.path = strings.Repeat(strconv.Itoa(i), 100)
c.tags = []string {strings.Repeat("a",100)}
}
dir1 := imgdir{imgs1}
dirs[strconv.Itoa(i)] = dir1
if i % 99 == 0 {
var stat runtime.MemStats
runtime.ReadMemStats(&stat)
log.Printf("alloc:%d, heapAlloc:%d \n", stat.Alloc, stat.HeapAlloc)
}
}
end := time.Now()
log.Println("time :", end.Sub(start))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment