...

Source file src/runtime/testdata/testprog/memprof.go

Documentation: runtime/testdata/testprog

     1  // Copyright 2016 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  	"bytes"
     9  	"fmt"
    10  	"os"
    11  	"runtime"
    12  	"runtime/pprof"
    13  )
    14  
    15  func init() {
    16  	register("MemProf", MemProf)
    17  }
    18  
    19  var memProfBuf bytes.Buffer
    20  var memProfStr string
    21  
    22  func MemProf() {
    23  	// Force heap sampling for determinism.
    24  	runtime.MemProfileRate = 1
    25  
    26  	for i := 0; i < 10; i++ {
    27  		fmt.Fprintf(&memProfBuf, "%*d\n", i, i)
    28  	}
    29  	memProfStr = memProfBuf.String()
    30  
    31  	runtime.GC()
    32  
    33  	f, err := os.CreateTemp("", "memprof")
    34  	if err != nil {
    35  		fmt.Fprintln(os.Stderr, err)
    36  		os.Exit(2)
    37  	}
    38  
    39  	if err := pprof.WriteHeapProfile(f); err != nil {
    40  		fmt.Fprintln(os.Stderr, err)
    41  		os.Exit(2)
    42  	}
    43  
    44  	name := f.Name()
    45  	if err := f.Close(); err != nil {
    46  		fmt.Fprintln(os.Stderr, err)
    47  		os.Exit(2)
    48  	}
    49  
    50  	fmt.Println(name)
    51  }
    52  

View as plain text