github.com/euank/go@v0.0.0-20160829210321-495514729181/src/runtime/testdata/testprogcgo/threadpprof.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 // +build !plan9,!windows 6 7 package main 8 9 // Run a slow C function saving a CPU profile. 10 11 /* 12 #include <stdint.h> 13 #include <time.h> 14 #include <pthread.h> 15 16 int threadSalt1; 17 int threadSalt2; 18 19 void cpuHogThread() { 20 int foo = threadSalt1; 21 int i; 22 23 for (i = 0; i < 100000; i++) { 24 if (foo > 0) { 25 foo *= foo; 26 } else { 27 foo *= foo + 1; 28 } 29 } 30 threadSalt2 = foo; 31 } 32 33 static int cpuHogThreadCount; 34 35 struct cgoTracebackArg { 36 uintptr_t context; 37 uintptr_t sigContext; 38 uintptr_t* buf; 39 uintptr_t max; 40 }; 41 42 // pprofCgoThreadTraceback is passed to runtime.SetCgoTraceback. 43 // For testing purposes it pretends that all CPU hits in C code are in cpuHog. 44 void pprofCgoThreadTraceback(void* parg) { 45 struct cgoTracebackArg* arg = (struct cgoTracebackArg*)(parg); 46 arg->buf[0] = (uintptr_t)(cpuHogThread) + 0x10; 47 arg->buf[1] = 0; 48 __sync_add_and_fetch(&cpuHogThreadCount, 1); 49 } 50 51 // getCPUHogThreadCount fetches the number of times we've seen cpuHogThread 52 // in the traceback. 53 int getCPUHogThreadCount() { 54 return __sync_add_and_fetch(&cpuHogThreadCount, 0); 55 } 56 */ 57 import "C" 58 59 import ( 60 "fmt" 61 "io/ioutil" 62 "os" 63 "runtime" 64 "runtime/pprof" 65 "time" 66 "unsafe" 67 ) 68 69 func init() { 70 register("CgoPprofThread", CgoPprofThread) 71 } 72 73 func CgoPprofThread() { 74 runtime.SetCgoTraceback(0, unsafe.Pointer(C.pprofCgoThreadTraceback), nil, nil) 75 76 f, err := ioutil.TempFile("", "prof") 77 if err != nil { 78 fmt.Fprintln(os.Stderr, err) 79 os.Exit(2) 80 } 81 82 if err := pprof.StartCPUProfile(f); err != nil { 83 fmt.Fprintln(os.Stderr, err) 84 os.Exit(2) 85 } 86 87 t0 := time.Now() 88 for C.getCPUHogThreadCount() < 2 && time.Since(t0) < time.Second { 89 time.Sleep(100 * time.Millisecond) 90 } 91 92 pprof.StopCPUProfile() 93 94 name := f.Name() 95 if err := f.Close(); err != nil { 96 fmt.Fprintln(os.Stderr, err) 97 os.Exit(2) 98 } 99 100 fmt.Println(name) 101 }