-
-
Notifications
You must be signed in to change notification settings - Fork 274
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add cpu profiling capability to base module
- Loading branch information
Showing
2 changed files
with
54 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
package base | ||
|
||
import ( | ||
"context" | ||
"flag" | ||
"fmt" | ||
"os" | ||
"runtime/pprof" | ||
) | ||
|
||
var ( | ||
cpuProfile string | ||
) | ||
|
||
func init() { | ||
flag.StringVar(&cpuProfile, "cpuprofile", "", "write cpu profile to `file`") | ||
} | ||
|
||
func startProfiling() { | ||
if cpuProfile != "" { | ||
module.StartWorker("cpu profiler", cpuProfiler) | ||
} | ||
} | ||
|
||
func cpuProfiler(ctx context.Context) error { | ||
f, err := os.Create(cpuProfile) | ||
if err != nil { | ||
return fmt.Errorf("could not create CPU profile: %s", err) | ||
} | ||
if err := pprof.StartCPUProfile(f); err != nil { | ||
return fmt.Errorf("could not start CPU profile: %s", err) | ||
} | ||
|
||
// wait for shutdown | ||
<-ctx.Done() | ||
|
||
pprof.StopCPUProfile() | ||
err = f.Close() | ||
if err != nil { | ||
return fmt.Errorf("failed to close CPU profile file: %s", err) | ||
} | ||
return nil | ||
} |