0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

go pprof snippet

Last updated at Posted at 2021-10-20

cpu, trace, memory, block and goroutine

cw, err := os.Getwd()
	if err != nil {
		panic(err)
	}

	f, err := os.Create(path.Join(cw, "cpu.prof"))
	if err != nil {
		panic(err)
	}
	defer f.Close()
	if err := pprof.StartCPUProfile(f); err != nil {
		log.Fatal("could not start CPU profile: ", err)
	}
	defer pprof.StopCPUProfile()

	tf, err := os.Create(path.Join(cw, "trace.out"))
	if err != nil {
		panic(err)
	}
	defer tf.Close()
	if err := trace.Start(tf); err != nil {
		log.Fatalf("profile: could not start trace: %v", err)
	}
	defer trace.Stop()

	old := runtime.MemProfileRate
	runtime.MemProfileRate = 4096
	defer func() {
		cw, err := os.Getwd()
		if err != nil {
			panic(err)
		}
		f, err := os.Create(path.Join(cw, "mem.prof"))
		if err != nil {
			panic(err)
		}
		defer f.Close()

		defer func() {
			runtime.MemProfileRate = old
		}()

		runtime.GC()
		if err := pprof.WriteHeapProfile(f); err != nil {
			log.Fatal("could not write memory profile: ", err)
		}
	}()

	runtime.SetBlockProfileRate(1)
	defer func() {

		cw, err := os.Getwd()
		if err != nil {
			panic(err)
		}
		f, err := os.Create(path.Join(cw, "block.prof"))
		if err != nil {
			panic(err)
		}
		defer f.Close()

		runtime.SetBlockProfileRate(1)
		defer func() {
			pprof.Lookup("block").WriteTo(f, 0)
			runtime.SetBlockProfileRate(0)
		}()

	}()

	defer func() {

		cw, err := os.Getwd()
		if err != nil {
			panic(err)
		}
		f, err := os.Create(path.Join(cw, "goroutine.prof"))
		if err != nil {
			panic(err)
		}
		defer f.Close()

		runtime.SetBlockProfileRate(1)
		defer func() {
			if mp := pprof.Lookup("goroutine"); mp != nil {
				mp.WriteTo(f, 0)
			}
		}()

	}()
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?