aboutsummaryrefslogtreecommitdiffstats
path: root/pkg/tool/cmdprof.go
blob: 196a0cd24d1445eb793c788897732c80789b1e81 (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
// 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 tool

import (
	"os"
	"runtime"
	"runtime/pprof"
)

// installProfiling simplifies cpu/memory profiling for command line tools.
func installProfiling(cpuprof, memprof string) func() {
	res := func() {}
	if cpuprof != "" {
		f, err := os.Create(cpuprof)
		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 memprof != "" {
		prev := res
		res = func() {
			prev()
			f, err := os.Create(memprof)
			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
}