github.com/c12o16h1/go/src@v0.0.0-20200114212001-5a151c0f00ed/runtime/testdata/testprog/timeprof.go (about)

     1  // Copyright 2018 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  	"io/ioutil"
    10  	"os"
    11  	"runtime/pprof"
    12  	"time"
    13  )
    14  
    15  func init() {
    16  	register("TimeProf", TimeProf)
    17  }
    18  
    19  func TimeProf() {
    20  	f, err := ioutil.TempFile("", "timeprof")
    21  	if err != nil {
    22  		fmt.Fprintln(os.Stderr, err)
    23  		os.Exit(2)
    24  	}
    25  
    26  	if err := pprof.StartCPUProfile(f); err != nil {
    27  		fmt.Fprintln(os.Stderr, err)
    28  		os.Exit(2)
    29  	}
    30  
    31  	t0 := time.Now()
    32  	// We should get a profiling signal 100 times a second,
    33  	// so running for 1/10 second should be sufficient.
    34  	for time.Since(t0) < time.Second/10 {
    35  	}
    36  
    37  	pprof.StopCPUProfile()
    38  
    39  	name := f.Name()
    40  	if err := f.Close(); err != nil {
    41  		fmt.Fprintln(os.Stderr, err)
    42  		os.Exit(2)
    43  	}
    44  
    45  	fmt.Println(name)
    46  }