-profile: add memory profiling

during runtime, profiles can be downloaded from :6060/debug/pprof
for default dump, run with GOGC=off to get the full picture of allocations
This commit is contained in:
Norwin Roosen 2021-01-02 15:56:24 +01:00
parent e9fc8e6c48
commit 4d0a3635c0
No known key found for this signature in database
GPG Key ID: 24BC059DE24C43A3
1 changed files with 21 additions and 5 deletions

26
main.go
View File

@ -6,8 +6,11 @@ import (
"image" "image"
"log" "log"
"math/rand" "math/rand"
"net/http"
_ "net/http/pprof"
"os" "os"
"os/signal" "os/signal"
"runtime"
"runtime/pprof" "runtime/pprof"
"sync" "sync"
"time" "time"
@ -27,15 +30,15 @@ var (
y = flag.Int("y", 0, "Offset of posted image from top border") y = flag.Int("y", 0, "Offset of posted image from top border")
order = flag.String("order", "rtl", "Draw order (shuffle, ltr, rtl, ttb, btt)") order = flag.String("order", "rtl", "Draw order (shuffle, ltr, rtl, ttb, btt)")
fetchImgPath = flag.String("fetch", "", "Enable fetching the screen area to the given local file, updating it each second") fetchImgPath = flag.String("fetch", "", "Enable fetching the screen area to the given local file, updating it each second")
cpuprofile = flag.String("cpuprofile", "", "Destination file for CPU Profile") profile = flag.Bool("profile", false, "Enable profiling. See results with `go tool pprof cpu.prof mem.prof")
) )
func main() { func main() {
flag.Parse() flag.Parse()
rand.Seed(time.Now().UnixNano()) rand.Seed(time.Now().UnixNano())
task := runWithExitHandler(taskFromFlags) task := runWithExitHandler(taskFromFlags)
if *cpuprofile != "" { if *profile {
runWithProfiler(*cpuprofile, task) runWithProfiler(task)
} else { } else {
task() task()
} }
@ -139,13 +142,26 @@ func runWithExitHandler(task func(stop chan bool, wg *sync.WaitGroup)) func() {
} }
} }
func runWithProfiler(outfile string, task func()) { func runWithProfiler(task func()) {
f, err := os.Create(outfile) f, err := os.Create("cpu.prof")
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
defer f.Close() defer f.Close()
pprof.StartCPUProfile(f) pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile() defer pprof.StopCPUProfile()
go func() { http.ListenAndServe("localhost:6060", nil) }()
task() task()
f2, err := os.Create("mem.prof")
if err != nil {
log.Fatal(err)
}
defer f2.Close()
runtime.GC()
if err := pprof.WriteHeapProfile(f2); err != nil {
log.Fatal(err)
}
} }