blob: ab0396d16479464392c86f434c9c4212cf601227 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
// Copyright 2020 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
// Package cmdprof simplifies cpu/memory profiling for command line tools. Use as:
// flag.Parse()
// defer cmdprof.Install()()
package cmdprof
import (
"flag"
"fmt"
"os"
"runtime"
"runtime/pprof"
)
var (
flagCPUProfile = flag.String("cpuprofile", "", "write CPU profile to this file")
flagMEMProfile = flag.String("memprofile", "", "write memory profile to this file")
)
func Install() func() {
res := func() {}
failf := func(msg string, args ...interface{}) {
fmt.Fprintf(os.Stderr, msg+"\n", args...)
os.Exit(1)
}
if *flagCPUProfile != "" {
f, err := os.Create(*flagCPUProfile)
if err != nil {
failf("failed to create cpuprofile file: %v", err)
}
if err := pprof.StartCPUProfile(f); err != nil {
failf("failed to start cpu profile: %v", err)
}
res = func() {
pprof.StopCPUProfile()
f.Close()
}
}
if *flagMEMProfile != "" {
prev := res
res = func() {
prev()
f, err := os.Create(*flagMEMProfile)
if err != nil {
failf("failed to create memprofile file: %v", err)
}
defer f.Close()
runtime.GC()
if err := pprof.WriteHeapProfile(f); err != nil {
failf("failed to write mem profile: %v", err)
}
}
}
return res
}
|