Debian Codegraph @

libgo/go/runtime/testdata/testprogcgo/pprof.go

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