2014-04-11 Marc Glisse <marc.glisse@inria.fr>
[official-gcc.git] / libgo / go / runtime / mallocrep1.go
blobbc33e3a6b4b643ebd8dc9fbbeddd17774d4dd869
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // +build ignore
7 // Repeated malloc test.
9 package main
11 import (
12 "flag"
13 "fmt"
14 "runtime"
15 "strconv"
18 var chatty = flag.Bool("v", false, "chatty")
19 var reverse = flag.Bool("r", false, "reverse")
20 var longtest = flag.Bool("l", false, "long test")
22 var b []*byte
23 var stats = new(runtime.MemStats)
25 func OkAmount(size, n uintptr) bool {
26 if n < size {
27 return false
29 if size < 16*8 {
30 if n > size+16 {
31 return false
33 } else {
34 if n > size*9/8 {
35 return false
38 return true
41 func AllocAndFree(size, count int) {
42 defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(1))
43 if *chatty {
44 fmt.Printf("size=%d count=%d ...\n", size, count)
46 runtime.ReadMemStats(stats)
47 n1 := stats.Alloc
48 for i := 0; i < count; i++ {
49 b[i] = runtime.Alloc(uintptr(size))
50 base, n := runtime.Lookup(b[i])
51 if base != b[i] || !OkAmount(uintptr(size), n) {
52 println("lookup failed: got", base, n, "for", b[i])
53 panic("fail")
55 runtime.ReadMemStats(stats)
56 if stats.Sys > 1e9 {
57 println("too much memory allocated")
58 panic("fail")
61 runtime.ReadMemStats(stats)
62 n2 := stats.Alloc
63 if *chatty {
64 fmt.Printf("size=%d count=%d stats=%+v\n", size, count, *stats)
66 n3 := stats.Alloc
67 for j := 0; j < count; j++ {
68 i := j
69 if *reverse {
70 i = count - 1 - j
72 alloc := uintptr(stats.Alloc)
73 base, n := runtime.Lookup(b[i])
74 if base != b[i] || !OkAmount(uintptr(size), n) {
75 println("lookup failed: got", base, n, "for", b[i])
76 panic("fail")
78 runtime.Free(b[i])
79 runtime.ReadMemStats(stats)
80 if stats.Alloc != uint64(alloc-n) {
81 println("free alloc got", stats.Alloc, "expected", alloc-n, "after free of", n)
82 panic("fail")
84 if stats.Sys > 1e9 {
85 println("too much memory allocated")
86 panic("fail")
89 runtime.ReadMemStats(stats)
90 n4 := stats.Alloc
92 if *chatty {
93 fmt.Printf("size=%d count=%d stats=%+v\n", size, count, *stats)
95 if n2-n1 != n3-n4 {
96 println("wrong alloc count: ", n2-n1, n3-n4)
97 panic("fail")
101 func atoi(s string) int {
102 i, _ := strconv.Atoi(s)
103 return i
106 func main() {
107 runtime.MemProfileRate = 0 // disable profiler
108 flag.Parse()
109 b = make([]*byte, 10000)
110 if flag.NArg() > 0 {
111 AllocAndFree(atoi(flag.Arg(0)), atoi(flag.Arg(1)))
112 return
114 maxb := 1 << 22
115 if !*longtest {
116 maxb = 1 << 19
118 for j := 1; j <= maxb; j <<= 1 {
119 n := len(b)
120 max := uintptr(1 << 28)
121 if !*longtest {
122 max = uintptr(maxb)
124 if uintptr(j)*uintptr(n) > max {
125 n = int(max / uintptr(j))
127 if n < 10 {
128 n = 10
130 for m := 1; m <= n; {
131 AllocAndFree(j, m)
132 if m == n {
133 break
135 m = 5 * m / 4
136 if m < 4 {
139 if m > n {
140 m = n