|
| 1 | +// Copyright 2025 The Cockroach Authors. |
| 2 | +// |
| 3 | +// Use of this software is governed by the CockroachDB Software License |
| 4 | +// included in the /LICENSE file. |
| 5 | + |
| 6 | +package benchprof |
| 7 | + |
| 8 | +import ( |
| 9 | + "bytes" |
| 10 | + "os" |
| 11 | + "path/filepath" |
| 12 | + "regexp" |
| 13 | + "runtime" |
| 14 | + runtimepprof "runtime/pprof" |
| 15 | + "strings" |
| 16 | + "testing" |
| 17 | + |
| 18 | + "github.com/cockroachdb/cockroach/pkg/testutils/sniffarg" |
| 19 | + "github.com/google/pprof/profile" |
| 20 | +) |
| 21 | + |
| 22 | +// StopFn is a function that stops profiling. |
| 23 | +type StopFn func(testing.TB) |
| 24 | + |
| 25 | +// Stop stops profiling. |
| 26 | +func (f StopFn) Stop(tb testing.TB) { |
| 27 | + if f != nil { |
| 28 | + f(tb) |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +// StartAllProfiles starts collection of CPU, heap, and mutex profiles, if the |
| 33 | +// "-test.cpuprofile", "-test.memprofile", or "-test.mutexprofile" flags are |
| 34 | +// set. See StartCPUProfile, StartMemProfile, and StartMutexProfile for more |
| 35 | +// details. |
| 36 | +// |
| 37 | +// Example usage: |
| 38 | +// |
| 39 | +// func BenchmarkFoo(b *testing.B) { |
| 40 | +// // .. |
| 41 | +// b.Run("case", func(b *testing.B) { |
| 42 | +// defer benchprof.StartAllProfiles(b).Stop(b) |
| 43 | +// // Benchmark loop. |
| 44 | +// }) |
| 45 | +// } |
| 46 | +func StartAllProfiles(tb testing.TB) StopFn { |
| 47 | + cpuStop := StartCPUProfile(tb) |
| 48 | + memStop := StartMemProfile(tb) |
| 49 | + mutexStop := StartMutexProfile(tb) |
| 50 | + return func(b testing.TB) { |
| 51 | + cpuStop(b) |
| 52 | + memStop(b) |
| 53 | + mutexStop(b) |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +// StartCPUProfile starts collection of a CPU profile if the "-test.cpuprofile" |
| 58 | +// flag has been set. The profile will omit CPU samples collected prior to |
| 59 | +// calling StartCPUProfile, and include all allocations made until the returned |
| 60 | +// StopFn is called. |
| 61 | +// |
| 62 | +// Example usage: |
| 63 | +// |
| 64 | +// func BenchmarkFoo(b *testing.B) { |
| 65 | +// // .. |
| 66 | +// b.Run("case", func(b *testing.B) { |
| 67 | +// defer benchprof.StartCPUProfile(b).Stop(b) |
| 68 | +// // Benchmark loop. |
| 69 | +// }) |
| 70 | +// } |
| 71 | +// |
| 72 | +// The file name of the profile will include the prefix of the profile flags and |
| 73 | +// the benchmark names. For example, "foo_benchmark_thing_1.cpu" would be |
| 74 | +// created for a "BenchmarkThing/1" benchmark if the "-test.cpuprofile=foo.cpu" |
| 75 | +// flag is set. |
| 76 | +// |
| 77 | +// NB: The "foo.cpu" file will not be created because we must stop the global |
| 78 | +// CPU profiler in order to collect profiles that omit setup samples. |
| 79 | +func StartCPUProfile(tb testing.TB) StopFn { |
| 80 | + var cpuProfFile string |
| 81 | + if err := sniffarg.DoEnv("test.cpuprofile", &cpuProfFile); err != nil { |
| 82 | + tb.Fatal(err) |
| 83 | + } |
| 84 | + if cpuProfFile == "" { |
| 85 | + // Not CPU profile requested. |
| 86 | + return nil |
| 87 | + } |
| 88 | + |
| 89 | + prefix := profilePrefix(cpuProfFile) |
| 90 | + dir := outputDir(tb) |
| 91 | + if dir != "" { |
| 92 | + cpuProfFile = filepath.Join(dir, cpuProfFile) |
| 93 | + } |
| 94 | + |
| 95 | + // Hijack the harness's profile to make a clean profile. |
| 96 | + // The flag is set, so likely a CPU profile started by the Go harness is |
| 97 | + // running (unless -count is specified, but StopCPUProfile is idempotent). |
| 98 | + runtimepprof.StopCPUProfile() |
| 99 | + |
| 100 | + // Remove the harness's profile file. It would not be an accurate profile. |
| 101 | + _ = os.Remove(cpuProfFile) |
| 102 | + |
| 103 | + // Create a new profile file. |
| 104 | + fileName := profileFileName(tb, dir, prefix, "cpu") |
| 105 | + f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) |
| 106 | + if err != nil { |
| 107 | + tb.Fatal(err) |
| 108 | + } |
| 109 | + |
| 110 | + // Start profiling. |
| 111 | + if err := runtimepprof.StartCPUProfile(f); err != nil { |
| 112 | + tb.Fatal(err) |
| 113 | + } |
| 114 | + |
| 115 | + return func(b testing.TB) { |
| 116 | + runtimepprof.StopCPUProfile() |
| 117 | + if err := f.Close(); err != nil { |
| 118 | + b.Fatal(err) |
| 119 | + } |
| 120 | + } |
| 121 | +} |
| 122 | + |
| 123 | +// StartMemProfile starts collection of a heap profile if the "-test.memprofile" |
| 124 | +// flag has been set. The profile will omit memory allocations prior to calling |
| 125 | +// StartMemProfile, and include all allocations made until the returned StopFn |
| 126 | +// is called. |
| 127 | +// |
| 128 | +// Example usage: |
| 129 | +// |
| 130 | +// func BenchmarkFoo(b *testing.B) { |
| 131 | +// // .. |
| 132 | +// b.Run("case", func(b *testing.B) { |
| 133 | +// defer benchprof.StartMemProfile(b).Stop(b) |
| 134 | +// // Benchmark loop. |
| 135 | +// }) |
| 136 | +// } |
| 137 | +// |
| 138 | +// The file name of the profile will include the prefix of the profile flags and |
| 139 | +// the benchmark names. For example, "foo_benchmark_thing_1.mem" would be |
| 140 | +// created for a "BenchmarkThing/1" benchmark if the "-test.memprofile=foo.mem" |
| 141 | +// flag is set. |
| 142 | +// |
| 143 | +// NB: The "foo.mem" file will still be created and include all allocations made |
| 144 | +// during the entire duration of the benchmark. |
| 145 | +func StartMemProfile(tb testing.TB) StopFn { |
| 146 | + var memProfFile string |
| 147 | + if err := sniffarg.DoEnv("test.memprofile", &memProfFile); err != nil { |
| 148 | + tb.Fatal(err) |
| 149 | + } |
| 150 | + if memProfFile == "" { |
| 151 | + // No heap profile requested. |
| 152 | + return nil |
| 153 | + } |
| 154 | + |
| 155 | + prefix := profilePrefix(memProfFile) |
| 156 | + dir := outputDir(tb) |
| 157 | + if dir != "" { |
| 158 | + memProfFile = filepath.Join(dir, memProfFile) |
| 159 | + } |
| 160 | + |
| 161 | + // Create a new profile file. |
| 162 | + fileName := profileFileName(tb, dir, prefix, "mem") |
| 163 | + diffAllocs := diffProfile(func() []byte { |
| 164 | + p := runtimepprof.Lookup("allocs") |
| 165 | + var buf bytes.Buffer |
| 166 | + runtime.GC() |
| 167 | + if err := p.WriteTo(&buf, 0); err != nil { |
| 168 | + tb.Fatal(err) |
| 169 | + } |
| 170 | + return buf.Bytes() |
| 171 | + }) |
| 172 | + |
| 173 | + return func(b testing.TB) { |
| 174 | + if sl := diffAllocs(b); len(sl) > 0 { |
| 175 | + if err := os.WriteFile(fileName, sl, 0644); err != nil { |
| 176 | + b.Fatal(err) |
| 177 | + } |
| 178 | + } |
| 179 | + } |
| 180 | +} |
| 181 | + |
| 182 | +// StartMutexProfile starts collection of a mutex profile if the |
| 183 | +// "-test.cpuprofile" flag has been set. The profile will only collect data |
| 184 | +// between calling StartMutexProfile and calling the returned StopFn. |
| 185 | +// |
| 186 | +// Example usage: |
| 187 | +// |
| 188 | +// func BenchmarkFoo(b *testing.B) { |
| 189 | +// // .. |
| 190 | +// b.Run("case", func(b *testing.B) { |
| 191 | +// defer benchprof.StartMutexProfile(b).Stop(b) |
| 192 | +// // Benchmark loop. |
| 193 | +// }) |
| 194 | +// } |
| 195 | +// |
| 196 | +// The file name of the profile will include the prefix of the profile flags and |
| 197 | +// the benchmark names. For example, "foo_benchmark_thing_1.mutex" would be |
| 198 | +// created for a "BenchmarkThing/1" benchmark if the |
| 199 | +// "-test.mutexprofile=foo.mutex" flag is set. |
| 200 | +func StartMutexProfile(tb testing.TB) StopFn { |
| 201 | + var mutexProfFile string |
| 202 | + if err := sniffarg.DoEnv("test.mutexprofile", &mutexProfFile); err != nil { |
| 203 | + tb.Fatal(err) |
| 204 | + } |
| 205 | + if mutexProfFile == "" { |
| 206 | + // No mutex profile requested. |
| 207 | + return nil |
| 208 | + } |
| 209 | + |
| 210 | + prefix := profilePrefix(mutexProfFile) |
| 211 | + dir := outputDir(tb) |
| 212 | + if dir != "" { |
| 213 | + mutexProfFile = filepath.Join(dir, mutexProfFile) |
| 214 | + } |
| 215 | + |
| 216 | + // Create a new profile file. |
| 217 | + fileName := profileFileName(tb, dir, prefix, "mutex") |
| 218 | + diffAllocs := diffProfile(func() []byte { |
| 219 | + p := runtimepprof.Lookup("mutex") |
| 220 | + var buf bytes.Buffer |
| 221 | + if err := p.WriteTo(&buf, 0); err != nil { |
| 222 | + tb.Fatal(err) |
| 223 | + } |
| 224 | + return buf.Bytes() |
| 225 | + }) |
| 226 | + |
| 227 | + return func(b testing.TB) { |
| 228 | + if sl := diffAllocs(b); len(sl) > 0 { |
| 229 | + if err := os.WriteFile(fileName, sl, 0644); err != nil { |
| 230 | + b.Fatal(err) |
| 231 | + } |
| 232 | + } |
| 233 | + } |
| 234 | +} |
| 235 | + |
| 236 | +func diffProfile(take func() []byte) func(testing.TB) []byte { |
| 237 | + // The below is essentially cribbed from pprof.go in net/http/pprof. |
| 238 | + |
| 239 | + baseBytes := take() |
| 240 | + if baseBytes == nil { |
| 241 | + return func(tb testing.TB) []byte { return nil } |
| 242 | + } |
| 243 | + return func(b testing.TB) []byte { |
| 244 | + newBytes := take() |
| 245 | + pBase, err := profile.ParseData(baseBytes) |
| 246 | + if err != nil { |
| 247 | + b.Fatal(err) |
| 248 | + } |
| 249 | + pNew, err := profile.ParseData(newBytes) |
| 250 | + if err != nil { |
| 251 | + b.Fatal(err) |
| 252 | + } |
| 253 | + pBase.Scale(-1) |
| 254 | + pMerged, err := profile.Merge([]*profile.Profile{pBase, pNew}) |
| 255 | + if err != nil { |
| 256 | + b.Fatal(err) |
| 257 | + } |
| 258 | + pMerged.TimeNanos = pNew.TimeNanos |
| 259 | + pMerged.DurationNanos = pNew.TimeNanos - pBase.TimeNanos |
| 260 | + |
| 261 | + buf := bytes.Buffer{} |
| 262 | + if err := pMerged.Write(&buf); err != nil { |
| 263 | + b.Fatal(err) |
| 264 | + } |
| 265 | + return buf.Bytes() |
| 266 | + } |
| 267 | +} |
| 268 | + |
| 269 | +func outputDir(tb testing.TB) string { |
| 270 | + var dir string |
| 271 | + if err := sniffarg.DoEnv("test.outputdir", &dir); err != nil { |
| 272 | + tb.Fatal(err) |
| 273 | + } |
| 274 | + return dir |
| 275 | +} |
| 276 | + |
| 277 | +func profilePrefix(profileArg string) string { |
| 278 | + i := strings.Index(profileArg, ".") |
| 279 | + if i == -1 { |
| 280 | + return profileArg |
| 281 | + } |
| 282 | + return profileArg[:i] |
| 283 | +} |
| 284 | + |
| 285 | +func profileFileName(tb testing.TB, outputDir, prefix, suffix string) string { |
| 286 | + saniRE := regexp.MustCompile(`\W+`) |
| 287 | + testName := strings.TrimPrefix(tb.Name(), "Benchmark") |
| 288 | + testName = strings.ToLower(testName) |
| 289 | + testName = saniRE.ReplaceAllString(testName, "_") |
| 290 | + |
| 291 | + fileName := prefix + "_" + testName + "." + suffix |
| 292 | + if outputDir != "" { |
| 293 | + fileName = filepath.Join(outputDir, fileName) |
| 294 | + } |
| 295 | + return fileName |
| 296 | +} |
0 commit comments