github.com/geraldss/go/src@v0.0.0-20210511222824-ac7d0ebfc235/runtime/testdata/testprogcgo/pprof.go (about)

     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  // Run a slow C function saving a CPU profile.
     8  
     9  /*
    10  #include <stdint.h>
    11  
    12  int salt1;
    13  int salt2;
    14  
    15  void cpuHog() {
    16  	int foo = salt1;
    17  	int i;
    18  
    19  	for (i = 0; i < 100000; i++) {
    20  		if (foo > 0) {
    21  			foo *= foo;
    22  		} else {
    23  			foo *= foo + 1;
    24  		}
    25  	}
    26  	salt2 = foo;
    27  }
    28  
    29  void cpuHog2() {
    30  }
    31  
    32  static int cpuHogCount;
    33  
    34  struct cgoTracebackArg {
    35  	uintptr_t  context;
    36  	uintptr_t  sigContext;
    37  	uintptr_t* buf;
    38  	uintptr_t  max;
    39  };
    40  
    41  // pprofCgoTraceback is passed to runtime.SetCgoTraceback.
    42  // For testing purposes it pretends that all CPU hits in C code are in cpuHog.
    43  // Issue #29034: At least 2 frames are required to verify all frames are captured
    44  // since runtime/pprof ignores the runtime.goexit base frame if it exists.
    45  void pprofCgoTraceback(void* parg) {
    46  	struct cgoTracebackArg* arg = (struct cgoTracebackArg*)(parg);
    47  	arg->buf[0] = (uintptr_t)(cpuHog) + 0x10;
    48  	arg->buf[1] = (uintptr_t)(cpuHog2) + 0x4;
    49  	arg->buf[2] = 0;
    50  	++cpuHogCount;
    51  }
    52  
    53  // getCpuHogCount fetches the number of times we've seen cpuHog in the
    54  // traceback.
    55  int getCpuHogCount() {
    56  	return cpuHogCount;
    57  }
    58  */
    59  import "C"
    60  
    61  import (
    62  	"fmt"
    63  	"os"
    64  	"runtime"
    65  	"runtime/pprof"
    66  	"time"
    67  	"unsafe"
    68  )
    69  
    70  func init() {
    71  	register("CgoPprof", CgoPprof)
    72  }
    73  
    74  func CgoPprof() {
    75  	runtime.SetCgoTraceback(0, unsafe.Pointer(C.pprofCgoTraceback), nil, nil)
    76  
    77  	f, err := os.CreateTemp("", "prof")
    78  	if err != nil {
    79  		fmt.Fprintln(os.Stderr, err)
    80  		os.Exit(2)
    81  	}
    82  
    83  	if err := pprof.StartCPUProfile(f); err != nil {
    84  		fmt.Fprintln(os.Stderr, err)
    85  		os.Exit(2)
    86  	}
    87  
    88  	t0 := time.Now()
    89  	for C.getCpuHogCount() < 2 && time.Since(t0) < time.Second {
    90  		C.cpuHog()
    91  	}
    92  
    93  	pprof.StopCPUProfile()
    94  
    95  	name := f.Name()
    96  	if err := f.Close(); err != nil {
    97  		fmt.Fprintln(os.Stderr, err)
    98  		os.Exit(2)
    99  	}
   100  
   101  	fmt.Println(name)
   102  }