Search code examples
goprofilingpprof

Go Profiling - Wrong file


I'm doing profiling in Go using github.com/pkg/profile and it's creating the file when I run my code, but the return comes from the example page code, how would it be to run through my code? thanks in advance

Code:

package main

import (
    "fmt"
    "github.com/pkg/profile"
    "time"
)

func main() {

    defer profile.Start(profile.MemProfile).Stop()

    var inicio = time.Now().UnixNano()

    var text = "Olá Mundo!"

    fmt.Println(text)

    var fim = time.Now().UnixNano()

    fmt.Println(fim - inicio)

}

Return:

enter image description here


Solution

  • You can change your profile output path to to your current working directory,

    profile.ProfilePath(path)
    

    If you are unable to make retrieve any samples, it either means your MemProfileRate is not small enough to actually capture small changes.

    If you are allocation less amount of memory, then set the MemProfileRate to lesser value, If you are allocating large amount of memory, just keep to default. If you think you capturing minor memory changes, then increase the MemProfileRate.

    profile.MemProfileRate(100)
    

    and one thing you shouldn't forget when you are using profile package is your call should be deferred.

    defer profile.Start(xxx).Stop()
    

    Here is the complete program.

    package main
    
    import (
        "os"
    
        "github.com/pkg/profile"
    )
    
    func main() {
        dir, _ := os.Getwd()
        defer profile.Start(profile.MemProfile, profile.MemProfileRate(100), profile.ProfilePath(dir)).Stop()
        //decrease mem profile rate for capturing more samples
        for i := 0; i < 10000; i++ {
            tmp := make([]byte, 100000)
            tmp[0] = tmp[1] << 0 //fake workload
        }
    }
    

    you can also set profile path for having the profile output in your current workign directory.