Fix recomputing diffs N times.
[lightning.git] / profile.go
1 package lightning
2
3 import (
4         "os"
5         "runtime"
6         "runtime/pprof"
7         "time"
8
9         log "github.com/sirupsen/logrus"
10 )
11
12 func writeProfilesPeriodically(outdir string) {
13         for range time.NewTicker(time.Minute).C {
14                 writeMemProfile(outdir)
15                 writeCPUProfile(outdir)
16         }
17 }
18
19 func writeCPUProfile(outdir string) {
20         f, err := os.OpenFile(outdir+"/cpu.prof~", os.O_CREATE|os.O_WRONLY, 0666)
21         if err != nil {
22                 log.Print(err)
23                 return
24         }
25         defer f.Close()
26         runtime.GC()
27         if err := pprof.StartCPUProfile(f); err != nil {
28                 log.Print(err)
29                 return
30         }
31         time.Sleep(time.Second)
32         pprof.StopCPUProfile()
33         err = f.Close()
34         if err != nil {
35                 log.Print(err)
36                 return
37         }
38         err = os.Rename(outdir+"/cpu.prof~", outdir+"/cpu.prof")
39         if err != nil {
40                 log.Print(err)
41         }
42         return
43 }
44
45 func writeMemProfile(outdir string) {
46         f, err := os.OpenFile(outdir+"/mem.prof~", os.O_CREATE|os.O_WRONLY, 0666)
47         if err != nil {
48                 log.Print(err)
49                 return
50         }
51         defer f.Close()
52         runtime.GC()
53         if err := pprof.WriteHeapProfile(f); err != nil {
54                 log.Print(err)
55                 return
56         }
57         err = f.Close()
58         if err != nil {
59                 log.Print(err)
60                 return
61         }
62         err = os.Rename(outdir+"/mem.prof~", outdir+"/mem.prof")
63         if err != nil {
64                 log.Print(err)
65         }
66         return
67 }