分析go程序时索引超出范围错误

This blog post provides instructions about how to profile a golang program using the runtime/pprof package.

In addition to the above mentioned package import, it says (STEP 1) to add this code to the main func

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

func main() {
    flag.Parse()
    if *cpuprofile != "" {
        f, err := os.Create(*cpuprofile)
        if err != nil {
            log.Fatal(err)
        }
        pprof.StartCPUProfile(f)
        defer pprof.StopCPUProfile()
    }

Then (STEP2) to run the binary (in this case named ./havlak1) passing the name of a file (with extension .prof) to the cpuprofile flag

 ./havlak1 -cpuprofile=havlak1.prof

Then, after the program stops, (STEP 3) to pass the binary and the .prof file to the go tool pprof program

$ go tool pprof havlak1 havlak1.prof
Welcome to pprof!  For help, type 'help'.
(pprof)

At this point, the blog author runs the top10 command to get some output.

I have done each of those steps with my program (but with different binary and .prof file name). However, when I run the top10 command, my program panics with an index out of range error. If I do

cat myfile.prof

to check the contents of the .prof file, there is no output.

Question: is there a step missing in the blog post or what might I be doing wrong or not doing for the .prof file to be empty?

Update

Just to clarify, after starting the binary with the cpu flag like this

./havlak1 -cpuprofile=havlak1.prof

I visit the routes of my application a bunch of times to give it an opportunity to collect data. After I stop the program, I do cat filename.prof and it's empty

Once I run this command

go tool pprof havlak1 havlak1.prof

I can obviously no longer click around my application because the binary isn't running. (I'm assuming the binary is passed to the go tool pprof havlak1 for reasons other than to run the program again/keep it running)

Update

Do I have to include code to manually close the file it writes to? I am able to profile my application using a wrapper program github.com/davecheney/profile, which has a line that closes the file that's been opened.

It sounds like the file isn't being written and it looks like you are using a defer for the profile to stop. If the application exits before that defer can run you won't get the profile written.

You could try to stop the profiling at the end without using a defer statement.

You could make sure the issue is your code and not your machine by writing a simple test and running go test --cpuprofile=cpu.prof ( all go tests can be profiled using that flag automatically) and then viewing the results by go tool pprof mypackage.test cpu.prof