Skip to content

Commit

Permalink
[chore] optional pprof server
Browse files Browse the repository at this point in the history
  • Loading branch information
robinovitch61 committed Feb 3, 2025
1 parent 760310d commit 5762777
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 15 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@ kl
.DS_Store
*.log
*.txt
cpu.prof
*.prof
20 changes: 18 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -176,10 +176,26 @@ kubectl --context k3d-test2 port-forward services/flask-service 5000:5000
curl http://localhost:5000/status
```

To create a cpu profile, set the environment variable `KL_CPU_PROFILE=1`, run the app, then run e.g.
To run with profiling available, set the environment variable `KL_PPROF_SERVER=1`, run the app, then run e.g.

```shell
go tool pprof -http=:8080 cpu.prof
# web ui for memory profile
go tool pprof -http=:8080 "http://localhost:6060/debug/pprof/heap"

# web ui for cpu profile
go tool pprof -http=:8080 "http://localhost:6060/debug/pprof/profile?seconds=15"

# explore memory profile in terminal
go tool pprof "http://localhost:6060/debug/pprof/heap"
> top
> peek ...
> traces ...

# explore cpu profile in terminal
go tool pprof "http://localhost:6060/debug/pprof/profile?seconds=15"
> top
> peek ...
> traces ...
```

## Manually Specify the `kl` Version at Build Time
Expand Down
22 changes: 10 additions & 12 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,23 +1,21 @@
package main

import (
"fmt"
"github.com/robinovitch61/kl/cmd"
"log"
"net/http"
_ "net/http/pprof" // register pprof endpoints
"os"
"runtime/pprof"
)

func main() {
if cpuProfile := os.Getenv("KL_CPU_PROFILE"); cpuProfile != "" {
f, err := os.Create("cpu.prof")
if err != nil {
log.Fatal("could not create CPU profile: ", err)
}
defer f.Close()
if err := pprof.StartCPUProfile(f); err != nil {
log.Fatal("could not start CPU profile: ", err)
}
defer pprof.StopCPUProfile()
if pprofServer := os.Getenv("KL_PPROF_SERVER"); pprofServer != "" {
port := "6060"
go func() {
if err := http.ListenAndServe(":"+port, nil); err != nil {
panic(fmt.Errorf("pprof server failed: %v", err))
}
}()
}

err := cmd.Execute()
Expand Down

0 comments on commit 5762777

Please sign in to comment.