github.com/c12o16h1/go/src@v0.0.0-20200114212001-5a151c0f00ed/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 "io/ioutil" 64 "os" 65 "runtime" 66 "runtime/pprof" 67 "time" 68 "unsafe" 69 ) 70 71 func init() { 72 register("CgoPprof", CgoPprof) 73 } 74 75 func CgoPprof() { 76 runtime.SetCgoTraceback(0, unsafe.Pointer(C.pprofCgoTraceback), nil, nil) 77 78 f, err := ioutil.TempFile("", "prof") 79 if err != nil { 80 fmt.Fprintln(os.Stderr, err) 81 os.Exit(2) 82 } 83 84 if err := pprof.StartCPUProfile(f); err != nil { 85 fmt.Fprintln(os.Stderr, err) 86 os.Exit(2) 87 } 88 89 t0 := time.Now() 90 for C.getCpuHogCount() < 2 && time.Since(t0) < time.Second { 91 C.cpuHog() 92 } 93 94 pprof.StopCPUProfile() 95 96 name := f.Name() 97 if err := f.Close(); err != nil { 98 fmt.Fprintln(os.Stderr, err) 99 os.Exit(2) 100 } 101 102 fmt.Println(name) 103 }