refactor(ipfs2/main) change the way we handle profiling
Brian Tiger Chow committed
Nov 10, 2014 at 23:25 UTC
74b38cb65fc0612c2679a8df0547ff88ffc57314
1 file changed
+28
-10
cmd/ipfs2/main.go
+28
-10
@@ -26,12 +26,11 @@ import (
26
var log = u.Logger("cmd/ipfs")
27
28
const (
29
- heapProfile = "ipfs.mprof"
29
+ cpuProfile = "ipfs.cpuprof"
30
+ heapProfile = "ipfs.memprof"
31
errorFormat = "ERROR: %v\n\n"
32
)
33
33
-var ofi io.WriteCloser
34
-
34
func main() {
35
err := run()
36
if err != nil {
@@ -58,15 +57,12 @@ func run() error {
57
u.SetAllLoggers(logging.DEBUG)
58
}
59
61
- // if debugging, setup profiling.
60
if u.Debug {
63
- var err error
64
- ofi, err = os.Create("cpu.prof")
61
+ stopProfilingFunc, err := startProfiling()
62
if err != nil {
63
return err
64
}
68
-
69
- pprof.StartCPUProfile(ofi)
65
+ defer stopProfilingFunc() // to be executed as late as possible
66
}
67
68
helpTextDisplayed, err := handleHelpOption(req, root)
@@ -228,7 +224,7 @@ func outputResponse(res cmds.Response, root *cmds.Command) error {
224
}
225
}
226
231
- emptyErr := errors.New("") // already displayed error text, but want to exit(1)
227
+ emptyErr := errors.New("") // already displayed error text
228
return emptyErr
229
}
230
@@ -266,12 +262,34 @@ func getConfig(path string) (*config.Config, error) {
262
return config.Load(configFile)
263
}
264
265
+// startProfiling begins CPU profiling and returns a `stop` function to be
266
+// executed as late as possible. The stop function captures the memprofile.
267
+func startProfiling() (func(), error) {
268
+
269
+ // start CPU profiling as early as possible
270
+ ofi, err := os.Create(cpuProfile)
271
+ if err != nil {
272
+ return nil, err
273
+ }
274
+ pprof.StartCPUProfile(ofi)
275
+
276
+ stopProfiling := func() {
277
+ pprof.StopCPUProfile()
278
+ defer ofi.Close() // captured by the closure
279
+ err := writeHeapProfileToFile()
280
+ if err != nil {
281
+ log.Critical(err)
282
+ }
283
+ }
284
+ return stopProfiling, nil
285
+}
286
+
287
func writeHeapProfileToFile() error {
288
mprof, err := os.Create(heapProfile)
289
if err != nil {
290
return err
291
}
274
- defer mprof.Close()
292
+ defer mprof.Close() // _after_ writing the heap profile
293
return pprof.WriteHeapProfile(mprof)
294
}
295