gc_test.go 1.24 KB
Newer Older
1 2 3 4
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

5 6 7 8 9 10 11 12
package runtime_test

import (
	"runtime"
	"testing"
)

func TestGcSys(t *testing.T) {
13
	memstats := new(runtime.MemStats)
14
	runtime.GC()
15 16
	runtime.ReadMemStats(memstats)
	sys := memstats.Sys
17

18 19
	runtime.MemProfileRate = 0 // disable profiler

20 21 22 23 24
	itercount := 1000000
	if testing.Short() {
		itercount = 100000
	}
	for i := 0; i < itercount; i++ {
25 26 27 28
		workthegc()
	}

	// Should only be using a few MB.
Russ Cox's avatar
Russ Cox committed
29
	// We allocated 100 MB or (if not short) 1 GB.
30 31
	runtime.ReadMemStats(memstats)
	if sys > memstats.Sys {
32 33
		sys = 0
	} else {
34
		sys = memstats.Sys - sys
35 36
	}
	t.Logf("used %d extra bytes", sys)
Russ Cox's avatar
Russ Cox committed
37
	if sys > 16<<20 {
38
		t.Fatalf("using too much memory: %d bytes", sys)
39 40 41 42 43 44
	}
}

func workthegc() []byte {
	return make([]byte, 1029)
}
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60

func TestGcDeepNesting(t *testing.T) {
	type T [2][2][2][2][2][2][2][2][2][2]*int
	a := new(T)

	// Prevent the compiler from applying escape analysis.
	// This makes sure new(T) is allocated on heap, not on the stack.
	t.Logf("%p", a)

	a[0][0][0][0][0][0][0][0][0][0] = new(int)
	*a[0][0][0][0][0][0][0][0][0][0] = 13
	runtime.GC()
	if *a[0][0][0][0][0][0][0][0][0][0] != 13 {
		t.Fail()
	}
}