StartCPUProfile starts CPU profiling, writing to the specified directory when stopped.
(profileDir string)
| 73 | |
| 74 | // StartCPUProfile starts CPU profiling, writing to the specified directory when stopped. |
| 75 | func (c *CPUProfiler) StartCPUProfile(profileDir string) error { |
| 76 | c.mu.Lock() |
| 77 | defer c.mu.Unlock() |
| 78 | |
| 79 | if c.session != nil { |
| 80 | return errors.New("CPU profiling already in progress") |
| 81 | } |
| 82 | |
| 83 | if err := os.MkdirAll(profileDir, 0o755); err != nil { |
| 84 | return fmt.Errorf("failed to create profile directory: %w", err) |
| 85 | } |
| 86 | |
| 87 | cpuProfilePath := filepath.Join(profileDir, fmt.Sprintf("%d-%d-cpuprofile.pb.gz", os.Getpid(), time.Now().UnixMilli())) |
| 88 | cpuFile, err := os.Create(cpuProfilePath) |
| 89 | if err != nil { |
| 90 | return fmt.Errorf("failed to create CPU profile file: %w", err) |
| 91 | } |
| 92 | |
| 93 | if err := pprof.StartCPUProfile(cpuFile); err != nil { |
| 94 | cpuFile.Close() |
| 95 | os.Remove(cpuProfilePath) |
| 96 | return fmt.Errorf("failed to start CPU profile: %w", err) |
| 97 | } |
| 98 | |
| 99 | c.session = &ProfileSession{ |
| 100 | cpuFilePath: cpuProfilePath, |
| 101 | cpuFile: cpuFile, |
| 102 | logWriter: io.Discard, |
| 103 | } |
| 104 | return nil |
| 105 | } |
| 106 | |
| 107 | // StopCPUProfile stops CPU profiling and returns the path to the profile file. |
| 108 | func (c *CPUProfiler) StopCPUProfile() (string, error) { |
no test coverage detected