Last active
August 18, 2022 18:49
-
-
Save ntsd/5efa06bb09b8bd3b9f0e43990451ae73 to your computer and use it in GitHub Desktop.
pprof CPU and Heap profiling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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