本文整理汇总了Golang中runtime.SetBlockProfileRate函数的典型用法代码示例。如果您正苦于以下问题:Golang SetBlockProfileRate函数的具体用法?Golang SetBlockProfileRate怎么用?Golang SetBlockProfileRate使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了SetBlockProfileRate函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: HandleBlockProfileRate
func (s *WebServer) HandleBlockProfileRate(w http.ResponseWriter, r *http.Request) {
rateStr := r.URL.Query().Get("rate")
var info string
if len(rateStr) < 1 {
info = `
SetBlockProfileRate controls the fraction of goroutine blocking events that are reported in the blocking profile.
The profiler aims to sample an average of one blocking event per rate nanoseconds spent blocked.
To include every blocking event in the profile, pass rate = 1.
To turn off profiling entirely, pass rate <= 0.
`
writeResponseWithErr(w, info)
return
}
rate, err := strconv.Atoi(rateStr)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if rate <= 0 {
info = "disable profiling"
} else if rate == 1 {
info = "profile everything"
} else {
// r = int64(float64(rate) * float64(tickspersecond()) / (1000 * 1000 * 1000)) //log.Println()
info = fmt.Sprintln("profile with rate %i*tickspersecond / 1*10^9", rate)
}
log.Println(info)
runtime.SetBlockProfileRate(rate)
writeResponseWithErr(w, info)
}
示例2: main
func main() {
// Extract the command line arguments
relayPort, clusterId, rsaKey := parseFlags()
// Check for CPU profiling
if *cpuProfile != "" {
prof, err := os.Create(*cpuProfile)
if err != nil {
log.Fatal(err)
}
pprof.StartCPUProfile(prof)
defer pprof.StopCPUProfile()
}
// Check for lock contention profiling
if *blockProfile != "" {
prof, err := os.Create(*blockProfile)
if err != nil {
log.Fatal(err)
}
runtime.SetBlockProfileRate(1)
defer pprof.Lookup("block").WriteTo(prof, 0)
}
// Create and boot a new carrier
log.Printf("main: booting iris overlay...")
overlay := iris.New(clusterId, rsaKey)
if peers, err := overlay.Boot(); err != nil {
log.Fatalf("main: failed to boot iris overlay: %v.", err)
} else {
log.Printf("main: iris overlay converged with %v remote connections.", peers)
}
// Create and boot a new relay
log.Printf("main: booting relay service...")
rel, err := relay.New(relayPort, overlay)
if err != nil {
log.Fatalf("main: failed to create relay service: %v.", err)
}
if err := rel.Boot(); err != nil {
log.Fatalf("main: failed to boot relay: %v.", err)
}
// Capture termination signals
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt)
// Report success
log.Printf("main: iris successfully booted, listening on port %d.", relayPort)
// Wait for termination request, clean up and exit
<-quit
log.Printf("main: terminating relay service...")
if err := rel.Terminate(); err != nil {
log.Printf("main: failed to terminate relay service: %v.", err)
}
log.Printf("main: terminating carrier...")
if err := overlay.Shutdown(); err != nil {
log.Printf("main: failed to shutdown iris overlay: %v.", err)
}
log.Printf("main: iris terminated.")
}
示例3: startHTTP
func startHTTP(s *options.SchedulerServer) {
mux := http.NewServeMux()
healthz.InstallHandler(mux)
if s.EnableProfiling {
mux.HandleFunc("/debug/pprof/", pprof.Index)
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
if s.EnableContentionProfiling {
goruntime.SetBlockProfileRate(1)
}
}
if c, err := configz.New("componentconfig"); err == nil {
c.Set(s.KubeSchedulerConfiguration)
} else {
glog.Errorf("unable to register configz: %s", err)
}
configz.InstallHandler(mux)
mux.Handle("/metrics", prometheus.Handler())
server := &http.Server{
Addr: net.JoinHostPort(s.Address, strconv.Itoa(int(s.Port))),
Handler: mux,
}
glog.Fatal(server.ListenAndServe())
}
示例4: before
// before runs before all testing.
func before() {
if *memProfileRate > 0 {
runtime.MemProfileRate = *memProfileRate
}
if *cpuProfile != "" {
f, err := os.Create(toOutputDir(*cpuProfile))
if err != nil {
fmt.Fprintf(os.Stderr, "testing: %s", err)
return
}
if err := pprof.StartCPUProfile(f); err != nil {
fmt.Fprintf(os.Stderr, "testing: can't start cpu profile: %s", err)
f.Close()
return
}
// Could save f so after can call f.Close; not worth the effort.
}
if *blockProfile != "" && *blockProfileRate >= 0 {
runtime.SetBlockProfileRate(*blockProfileRate)
}
if *coverProfile != "" && cover.Mode == "" {
fmt.Fprintf(os.Stderr, "testing: cannot use -test.coverprofile because test binary was not built with coverage enabled\n")
os.Exit(2)
}
}
示例5: main
func main() {
runtime.MemProfileRate = 1
runtime.SetBlockProfileRate(1)
runtime.GOMAXPROCS(runtime.NumCPU())
flag.Parse()
http.HandleFunc("/", handleWelcome)
http.HandleFunc("/chat", handleChat)
http.Handle("/ws", websocket.Handler(handleWebsocket))
go http.ListenAndServe(*httpAddr, nil)
ln, err := net.Listen("tcp", *apiAddr)
if err != nil {
log.Fatal(err)
}
go func() {
for {
c, err := ln.Accept()
if err != nil {
log.Fatal(err)
}
go handleApi(c)
}
}()
log.Printf("serving http at %v, api at %v", *httpAddr, *apiAddr)
select {}
}
示例6: startProfiling
// Starts all profiles set on the options.
func (cmd *BenchCommand) startProfiling(options *BenchOptions) {
var err error
// Start CPU profiling.
if options.CPUProfile != "" {
cpuprofile, err = os.Create(options.CPUProfile)
if err != nil {
fmt.Fprintf(cmd.Stderr, "bench: could not create cpu profile %q: %v\n", options.CPUProfile, err)
os.Exit(1)
}
pprof.StartCPUProfile(cpuprofile)
}
// Start memory profiling.
if options.MemProfile != "" {
memprofile, err = os.Create(options.MemProfile)
if err != nil {
fmt.Fprintf(cmd.Stderr, "bench: could not create memory profile %q: %v\n", options.MemProfile, err)
os.Exit(1)
}
runtime.MemProfileRate = 4096
}
// Start fatal profiling.
if options.BlockProfile != "" {
blockprofile, err = os.Create(options.BlockProfile)
if err != nil {
fmt.Fprintf(cmd.Stderr, "bench: could not create block profile %q: %v\n", options.BlockProfile, err)
os.Exit(1)
}
runtime.SetBlockProfileRate(1)
}
}
示例7: benchStartProfiling
// Starts all profiles set on the options.
func benchStartProfiling(options *BenchOptions) {
var err error
// Start CPU profiling.
if options.CPUProfile != "" {
cpuprofile, err = os.Create(options.CPUProfile)
if err != nil {
fatal("bench: could not create cpu profile %q: %v", options.CPUProfile, err)
}
pprof.StartCPUProfile(cpuprofile)
}
// Start memory profiling.
if options.MemProfile != "" {
memprofile, err = os.Create(options.MemProfile)
if err != nil {
fatal("bench: could not create memory profile %q: %v", options.MemProfile, err)
}
runtime.MemProfileRate = 4096
}
// Start fatal profiling.
if options.BlockProfile != "" {
blockprofile, err = os.Create(options.BlockProfile)
if err != nil {
fatal("bench: could not create block profile %q: %v", options.BlockProfile, err)
}
runtime.SetBlockProfileRate(1)
}
}
示例8: main
func main() {
flag.Parse()
config := configure()
runtime.SetBlockProfileRate(1)
serverDbPath := filepath.Join(persistDir, "dispatchd-server.db")
msgDbPath := filepath.Join(persistDir, "messages.db")
var server = server.NewServer(serverDbPath, msgDbPath, config["users"].(map[string]interface{}), strictMode)
ln, err := net.Listen("tcp", fmt.Sprintf(":%d", amqpPort))
if err != nil {
fmt.Printf("Error!\n")
os.Exit(1)
}
fmt.Printf("Listening on port %d\n", amqpPort)
go func() {
adminserver.StartAdminServer(server, adminPort)
}()
for {
conn, err := ln.Accept()
if err != nil {
fmt.Printf("Error accepting connection!\n")
os.Exit(1)
}
go handleConnection(server, conn)
}
}
示例9: setBlockRateHandler
func setBlockRateHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) (interface{}, error) {
rate, err := strconv.Atoi(req.FormValue("rate"))
if err != nil {
return nil, http_api.Err{http.StatusBadRequest, fmt.Sprintf("invalid block rate : %s", err.Error())}
}
runtime.SetBlockProfileRate(rate)
return nil, nil
}
示例10: blockHandler
func blockHandler(w http.ResponseWriter, r *http.Request) {
debug, _ := strconv.Atoi(r.FormValue("debug"))
sec, _ := strconv.ParseInt(r.FormValue("seconds"), 10, 64)
if sec == 0 {
sec = 30
}
rate, _ := strconv.Atoi(r.FormValue("rate"))
if rate == 0 {
rate = 1
}
w.Header().Set("Content-Type", "application/octet-stream")
runtime.SetBlockProfileRate(rate)
time.Sleep(time.Duration(sec) * time.Second)
runtime.SetBlockProfileRate(0)
p := rpprof.Lookup("block")
p.WriteTo(w, debug)
}
示例11: startProfiler
func startProfiler() {
if cmdutil.Env("OPENSHIFT_PROFILE", "") == "web" {
go func() {
runtime.SetBlockProfileRate(1)
glog.Infof("Starting profiling endpoint at http://127.0.0.1:6060/debug/pprof/")
glog.Fatal(http.ListenAndServe("127.0.0.1:6060", nil))
}()
}
}
示例12: startProfiler
func startProfiler() {
if cmdutil.Env("OPENSHIFT_PROFILE", "") == "web" {
go func() {
runtime.SetBlockProfileRate(1)
profile_port := cmdutil.Env("OPENSHIFT_PROFILE_PORT", "6060")
glog.Infof(fmt.Sprintf("Starting profiling endpoint at http://127.0.0.1:%s/debug/pprof/", profile_port))
glog.Fatal(http.ListenAndServe(fmt.Sprintf("127.0.0.1:%s", profile_port), nil))
}()
}
}
示例13: TestBlockProfile
func TestBlockProfile(t *testing.T) {
type TestCase struct {
name string
f func()
re []string
}
tests := [...]TestCase{
{"chan recv", blockChanRecv, []string{`runtime\.chanrecv1`, `.*/src/runtime/chan.go`, `runtime/pprof_test\.blockChanRecv`, `.*/src/runtime/pprof/pprof_test.go`, `runtime/pprof_test\.TestBlockProfile`, `.*/src/runtime/pprof/pprof_test.go`}},
{"chan send", blockChanSend, []string{`runtime\.chansend1`, `.*/src/runtime/chan.go`, `runtime/pprof_test\.blockChanSend`, `.*/src/runtime/pprof/pprof_test.go`, `runtime/pprof_test\.TestBlockProfile`, `.*/src/runtime/pprof/pprof_test.go`}},
{"chan close", blockChanClose, []string{`runtime\.chanrecv1`, `.*/src/runtime/chan.go`, `runtime/pprof_test\.blockChanClose`, `.*/src/runtime/pprof/pprof_test.go`, `runtime/pprof_test\.TestBlockProfile`, `.*/src/runtime/pprof/pprof_test.go`}},
{"select recv async", blockSelectRecvAsync, []string{`runtime\.selectgo`, `.*/src/runtime/select.go`, `runtime/pprof_test\.blockSelectRecvAsync`, `.*/src/runtime/pprof/pprof_test.go`, `runtime/pprof_test\.TestBlockProfile`, `.*/src/runtime/pprof/pprof_test.go`}},
{"select send sync", blockSelectSendSync, []string{`runtime\.selectgo`, `.*/src/runtime/select.go`, `runtime/pprof_test\.blockSelectSendSync`, `.*/src/runtime/pprof/pprof_test.go`, `runtime/pprof_test\.TestBlockProfile`, `.*/src/runtime/pprof/pprof_test.go`}},
{"mutex", blockMutex, []string{`sync\.\(\*Mutex\)\.Lock`, `.*/src/sync/mutex\.go`, `runtime/pprof_test\.blockMutex`, `.*/src/runtime/pprof/pprof_test.go`, `runtime/pprof_test\.TestBlockProfile`, `.*/src/runtime/pprof/pprof_test.go`}},
{"cond", blockCond, []string{`sync\.\(\*Cond\)\.Wait`, `.*/src/sync/cond\.go`, `runtime/pprof_test\.blockCond`, `.*/src/runtime/pprof/pprof_test.go`, `runtime/pprof_test\.TestBlockProfile`, `.*/src/runtime/pprof/pprof_test.go`}},
}
runtime.SetBlockProfileRate(1)
defer runtime.SetBlockProfileRate(0)
for _, test := range tests {
test.f()
var prof bytes.Buffer
Lookup("block").WriteTo(&prof, 1)
parseProfile(t, prof, func(p *ProfileTest) {
for n := 0; n < len(test.re); n += 2 {
found := false
for i := range p.Function {
f := p.Function[i]
t.Log(f.Name, f.Filename)
if !regexp.MustCompile(strings.Replace(test.re[n], "\t", "\t+", -1)).MatchString(f.Name) || !regexp.MustCompile(strings.Replace(test.re[n+1], "\t", "\t+", -1)).MatchString(f.Filename) {
found = true
break
}
}
if !found {
t.Fatalf("have not found expected function %s from file %s", test.re[n], test.re[n+1])
}
}
})
}
}
示例14: init
func init() {
for _, item := range strings.Split(os.Getenv("GOPPROF"), ",") {
equalsPos := strings.IndexByte(item, '=')
var key, value string
if equalsPos < 0 {
key = item
} else {
key = item[:equalsPos]
value = item[equalsPos+1:]
}
if value != "" {
log.Printf("values not yet supported")
}
switch key {
case "http":
go func() {
var l net.Listener
for port := uint16(6061); port != 6060; port++ {
var err error
l, err = net.Listen("tcp", fmt.Sprintf("localhost:%d", port))
if err == nil {
break
}
}
if l == nil {
log.Print("unable to create envpprof listener for http")
return
}
defer l.Close()
log.Printf("envpprof serving http://%s", l.Addr())
log.Printf("error serving http on envpprof listener: %s", http.Serve(l, nil))
}()
case "cpu":
os.Mkdir(pprofDir, 0750)
f, err := ioutil.TempFile(pprofDir, "cpu")
if err != nil {
log.Printf("error creating cpu pprof file: %s", err)
break
}
err = pprof.StartCPUProfile(f)
if err != nil {
log.Printf("error starting cpu profiling: %s", err)
break
}
log.Printf("cpu profiling to file %q", f.Name())
case "block":
runtime.SetBlockProfileRate(1)
case "heap":
heap = true
}
}
}
示例15: main
func main() {
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
log.Printf("Current PID: %d", os.Getpid())
flag.Parse()
runtime.SetBlockProfileRate(1)
ctx, cancel := context.WithCancel(context.Background())
if *taskName == "" {
hostname, err := os.Hostname()
if err != nil {
log.Fatalf("Unable to get hostname, set --name: %s", err)
}
*taskName = hostname
}
cs := store_config.NewLocalConfigStore(filepath.Join(*storePath, "config.txt"), *taskName)
if err := cs.Start(ctx); err != nil {
log.Fatalf("Error starting config store: %s", err)
}
store_config.Set(cs)
log.Printf("Opening store")
ds := datastore.Open(ctx, *storePath)
log.Printf("Finished opening store, serving")
go rpc_server.Serve(ds)
go http_server.Serve(ds)
cs.UpdateThisState(ctx, oproto.ClusterMember_RUN)
shutdown := make(chan struct{})
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
for sig := range c {
log.Printf("Caught signal %s, shutting down", sig)
close(shutdown)
}
}()
<-shutdown
// Drain server
cs.UpdateThisState(ctx, oproto.ClusterMember_DRAIN)
// TODO(drain)
// Shut down server
cs.UpdateThisState(ctx, oproto.ClusterMember_SHUTDOWN)
cs.Stop()
cancel()
}