Skip to content

Instantly share code, notes, and snippets.

@ntsd
Last active August 18, 2022 18:49
Show Gist options
  • Save ntsd/5efa06bb09b8bd3b9f0e43990451ae73 to your computer and use it in GitHub Desktop.
Save ntsd/5efa06bb09b8bd3b9f0e43990451ae73 to your computer and use it in GitHub Desktop.
pprof CPU and Heap profiling
package main
import (
"os"
"io/fs"
"runtime"
"runtime/pprof"
)
func profiling(function func()) {
done := make(chan struct{})
err := os.Mkdir("./pprof", fs.ModePerm)
if err != nil {
if !os.IsExist(err) {
panic(err)
}
}
cpuW, err := os.Create("./pprof/cpu.pb.gz")
if err != nil {
panic(err)
}
defer cpuW.Close()
heapW, err := os.Create("./pprof/heap.pb.gz")
if err != nil {
panic(err)
}
defer heapW.Close()
go func(done chan struct{}) {
defer func() { done <- struct{}{} }()
pprof.StartCPUProfile(cpuW)
function()
pprof.StopCPUProfile()
}(done)
runtime.GC()
pprof.WriteHeapProfile(heapW)
<-done
}
func main() {
profiling(func() {
sieveOfEratosthenes(100000000)
})
}
// return list of primes less than N
func sieveOfEratosthenes(N int) (primes []int) {
b := make([]bool, N)
for i := 2; i < N; i++ {
if b[i] {
continue
}
primes = append(primes, i)
for k := i * i; k < N; k += i {
b[k] = true
}
}
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment