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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
| func main() { Mem(fmt.Sprintf("for start")) isp := make([]interface{}, 0, counter) for i := 0; i < counter; i++ { ssUser := User{ Name: strconv.Itoa(i), Age: i, Sage: i, Count: rand.Intn(counter), } isp = append(isp,ssUser) }
fmt.Println("isp占用的字节大小:「isp结构占用」", unsafe.Sizeof(isp)) fmt.Println("counter的切片占用的字节大小:", unsafe.Sizeof([counter]interface{}{})) t := time.Now().Unix() Mem(fmt.Sprintf("for all slice")) _ = QuickSortAll(isp, 0, len(isp)-1, func(a, b interface{}) bool { return a.(User).Count <= b.(User).Count }) fmt.Println("耗时: ", time.Now().Unix()-t, " S") Mem(fmt.Sprintf("for all end"))
i := 0 for { if i > 3 { break }
runtime.GC() Mem(fmt.Sprintf("for gc end")) time.Sleep(1 * time.Second) i++ }
for i := range isp { isp[i] = nil } isp = isp[:0]
runtime.GC() Mem(fmt.Sprintf("gc before new start %d", i)) for i := 0; i < counter; i++ { stmp := User{} stmp.Name = strconv.Itoa(i) stmp.Age = i stmp.Sage = i stmp.Count = rand.Intn(counter) isp = append(isp, stmp)
if i%1000000 == 0 { Mem(fmt.Sprintf("slice %d", i)) } } fmt.Println("isp占用的字节大小:「isp结构占用」", unsafe.Sizeof(isp)) ts := time.Now().Unix() Mem(fmt.Sprintf("for all slice")) _ = QuickSortAll(isp, 0, len(isp)-1, func(a, b interface{}) bool { return a.(User).Count <= b.(User).Count }) fmt.Println("耗时: ", time.Now().Unix()-ts, " S") Mem(fmt.Sprintf("for all end"))
ia := 0 for { if ia > 10 { break }
runtime.GC() Mem(fmt.Sprintf("for gc end")) time.Sleep(1 * time.Second) ia++ } }
func Mem(msg string) { var m runtime.MemStats runtime.ReadMemStats(&m) fmt.Println(msg, "系统内存:", m.Sys, " 常驻内存:", m.HeapInuse, " 堆上分配的,gc后会归还: ", m.HeapAlloc) }
|