github.com/google/syzkaller@v0.0.0-20240517125934-c0f1611a36d6/pkg/tool/cmdprof.go (about) 1 // Copyright 2020 syzkaller project authors. All rights reserved. 2 // Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file. 3 4 package tool 5 6 import ( 7 "os" 8 "runtime" 9 "runtime/pprof" 10 ) 11 12 // installProfiling simplifies cpu/memory profiling for command line tools. 13 func installProfiling(cpuprof, memprof string) func() { 14 res := func() {} 15 if cpuprof != "" { 16 f, err := os.Create(cpuprof) 17 if err != nil { 18 Failf("failed to create cpuprofile file: %v", err) 19 } 20 if err := pprof.StartCPUProfile(f); err != nil { 21 Failf("failed to start cpu profile: %v", err) 22 } 23 res = func() { 24 pprof.StopCPUProfile() 25 f.Close() 26 } 27 } 28 if memprof != "" { 29 prev := res 30 res = func() { 31 prev() 32 f, err := os.Create(memprof) 33 if err != nil { 34 Failf("failed to create memprofile file: %v", err) 35 } 36 defer f.Close() 37 runtime.GC() 38 if err := pprof.WriteHeapProfile(f); err != nil { 39 Failf("failed to write mem profile: %v", err) 40 } 41 } 42 } 43 return res 44 }