Basic cpu and memory profiling

suggest change

Add the following code in you main program.

var cpuprofile = flag.String("cpuprofile", "", "write cpu profile `file`")
var memprofile = flag.String("memprofile", "", "write memory profile to `file`")

func main() {
    if *cpuprofile != "" {
        f, err := os.Create(*cpuprofile)
        if err != nil {
            log.Fatal("could not create CPU profile: ", err)
        if err := pprof.StartCPUProfile(f); err != nil {
            log.Fatal("could not start CPU profile: ", err)
        defer pprof.StopCPUProfile()
    if *memprofile != "" {
        f, err := os.Create(*memprofile)
        if err != nil {
            log.Fatal("could not create memory profile: ", err)
        runtime.GC() // get up-to-date statistics
        if err := pprof.WriteHeapProfile(f); err != nil {
            log.Fatal("could not write memory profile: ", err)

After that build the go program if added in main go build main.go. Run main program with flags defined in code main.exe -cpuprofile -memprof If the profiling is done for test cases run the tests with same flags go test -cpuprofile -memprofile

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents