1package main
2
3import (
4 "log"
5 "os"
6 "runtime"
7 "runtime/pprof"
8 "runtime/trace"
9)
10
11func memprofile(mempath string) {
12 if mempath == "" {
13 return
14 }
15
16 f, err := os.Create(mempath)
17 xcheckf(err, "creating memory profile")
18 defer func() {
19 if err := f.Close(); err != nil {
20 log.Printf("closing memory profile: %v", err)
21 }
22 }()
23 runtime.GC() // get up-to-date statistics
24 err = pprof.WriteHeapProfile(f)
25 xcheckf(err, "writing memory profile")
26}
27
28func profile(cpupath, mempath string) func() {
29 if cpupath == "" {
30 return func() {
31 memprofile(mempath)
32 }
33 }
34
35 f, err := os.Create(cpupath)
36 xcheckf(err, "creating CPU profile")
37 err = pprof.StartCPUProfile(f)
38 xcheckf(err, "start CPU profile")
39 return func() {
40 pprof.StopCPUProfile()
41 if err := f.Close(); err != nil {
42 log.Printf("closing cpu profile: %v", err)
43 }
44 memprofile(mempath)
45 }
46}
47
48func traceExecution(path string) func() {
49 f, err := os.Create(path)
50 xcheckf(err, "create trace file")
51 trace.Start(f)
52 return func() {
53 trace.Stop()
54 err := f.Close()
55 xcheckf(err, "close trace file")
56 }
57}
58