github.com/aloncn/graphics-go@v0.0.1/src/runtime/testdata/testprog/gc.go (about)

     1  // Copyright 2015 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.
     4  
     5  package main
     6  
     7  import (
     8  	"fmt"
     9  	"os"
    10  	"runtime"
    11  	"time"
    12  )
    13  
    14  func init() {
    15  	register("GCFairness", GCFairness)
    16  	register("GCSys", GCSys)
    17  }
    18  
    19  func GCSys() {
    20  	runtime.GOMAXPROCS(1)
    21  	memstats := new(runtime.MemStats)
    22  	runtime.GC()
    23  	runtime.ReadMemStats(memstats)
    24  	sys := memstats.Sys
    25  
    26  	runtime.MemProfileRate = 0 // disable profiler
    27  
    28  	itercount := 100000
    29  	for i := 0; i < itercount; i++ {
    30  		workthegc()
    31  	}
    32  
    33  	// Should only be using a few MB.
    34  	// We allocated 100 MB or (if not short) 1 GB.
    35  	runtime.ReadMemStats(memstats)
    36  	if sys > memstats.Sys {
    37  		sys = 0
    38  	} else {
    39  		sys = memstats.Sys - sys
    40  	}
    41  	if sys > 16<<20 {
    42  		fmt.Printf("using too much memory: %d bytes\n", sys)
    43  		return
    44  	}
    45  	fmt.Printf("OK\n")
    46  }
    47  
    48  func workthegc() []byte {
    49  	return make([]byte, 1029)
    50  }
    51  
    52  func GCFairness() {
    53  	runtime.GOMAXPROCS(1)
    54  	f, err := os.Open("/dev/null")
    55  	if os.IsNotExist(err) {
    56  		// This test tests what it is intended to test only if writes are fast.
    57  		// If there is no /dev/null, we just don't execute the test.
    58  		fmt.Println("OK")
    59  		return
    60  	}
    61  	if err != nil {
    62  		fmt.Println(err)
    63  		os.Exit(1)
    64  	}
    65  	for i := 0; i < 2; i++ {
    66  		go func() {
    67  			for {
    68  				f.Write([]byte("."))
    69  			}
    70  		}()
    71  	}
    72  	time.Sleep(10 * time.Millisecond)
    73  	fmt.Println("OK")
    74  }