| 1 |
//go:build pprof |
| 2 |
// +build pprof |
| 3 |
|
| 4 |
package fzf |
| 5 |
|
| 6 |
import ( |
| 7 |
"fmt" |
| 8 |
"os" |
| 9 |
"runtime" |
| 10 |
"runtime/pprof" |
| 11 |
|
| 12 |
"github.com/junegunn/fzf/src/util" |
| 13 |
) |
| 14 |
|
| 15 |
func (o *Options) initProfiling() error { |
| 16 |
if o.CPUProfile != "" { |
| 17 |
f, err := os.Create(o.CPUProfile) |
| 18 |
if err != nil { |
| 19 |
return fmt.Errorf("could not create CPU profile: %w", err) |
| 20 |
} |
| 21 |
|
| 22 |
if err := pprof.StartCPUProfile(f); err != nil { |
| 23 |
return fmt.Errorf("could not start CPU profile: %w", err) |
| 24 |
} |
| 25 |
|
| 26 |
util.AtExit(func() { |
| 27 |
pprof.StopCPUProfile() |
| 28 |
if err := f.Close(); err != nil { |
| 29 |
fmt.Fprintln(os.Stderr, "Error: closing cpu profile:", err) |
| 30 |
} |
| 31 |
}) |
| 32 |
} |
| 33 |
|
| 34 |
stopProfile := func(name string, f *os.File) { |
| 35 |
if err := pprof.Lookup(name).WriteTo(f, 0); err != nil { |
| 36 |
fmt.Fprintf(os.Stderr, "Error: could not write %s profile: %v\n", name, err) |
| 37 |
} |
| 38 |
if err := f.Close(); err != nil { |
| 39 |
fmt.Fprintf(os.Stderr, "Error: closing %s profile: %v\n", name, err) |
| 40 |
} |
| 41 |
} |
| 42 |
|
| 43 |
if o.MEMProfile != "" { |
| 44 |
f, err := os.Create(o.MEMProfile) |
| 45 |
if err != nil { |
| 46 |
return fmt.Errorf("could not create MEM profile: %w", err) |
| 47 |
} |
| 48 |
util.AtExit(func() { |
| 49 |
runtime.GC() |
| 50 |
stopProfile("allocs", f) |
| 51 |
}) |
| 52 |
} |
| 53 |
|
| 54 |
if o.BlockProfile != "" { |
| 55 |
runtime.SetBlockProfileRate(1) |
| 56 |
f, err := os.Create(o.BlockProfile) |
| 57 |
if err != nil { |
| 58 |
return fmt.Errorf("could not create BLOCK profile: %w", err) |
| 59 |
} |
| 60 |
util.AtExit(func() { stopProfile("block", f) }) |
| 61 |
} |
| 62 |
|
| 63 |
if o.MutexProfile != "" { |
| 64 |
runtime.SetMutexProfileFraction(1) |
| 65 |
f, err := os.Create(o.MutexProfile) |
| 66 |
if err != nil { |
| 67 |
return fmt.Errorf("could not create MUTEX profile: %w", err) |
| 68 |
} |
| 69 |
util.AtExit(func() { stopProfile("mutex", f) }) |
| 70 |
} |
| 71 |
|
| 72 |
return nil |
| 73 |
} |