aboutsummaryrefslogtreecommitdiff
path: root/cmd/syncthing/heapprof.go
blob: a4631451fc223ef108bcd84c682daa8baf8c2d9f (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
// Copyright (C) 2014 Jakob Borg and Contributors (see the CONTRIBUTORS file).
// All rights reserved. Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.

package main

import (
	"fmt"
	"os"
	"runtime"
	"runtime/pprof"
	"syscall"
	"time"
)

func init() {
	if innerProcess && os.Getenv("STHEAPPROFILE") != "" {
		l.Debugln("Starting heap profiling")
		go saveHeapProfiles()
	}
}

func saveHeapProfiles() {
	runtime.MemProfileRate = 1
	var memstats, prevMemstats runtime.MemStats

	t0 := time.Now()
	for t := range time.NewTicker(250 * time.Millisecond).C {
		startms := int(t.Sub(t0).Seconds() * 1000)
		runtime.ReadMemStats(&memstats)
		if memstats.HeapInuse > prevMemstats.HeapInuse {
			fd, err := os.Create(fmt.Sprintf("heap-%05d-%07d.pprof", syscall.Getpid(), startms))
			if err != nil {
				panic(err)
			}
			err = pprof.WriteHeapProfile(fd)
			if err != nil {
				panic(err)
			}
			err = fd.Close()
			if err != nil {
				panic(err)
			}
			prevMemstats = memstats
		}
	}
}