Golang StopCPUProfile示例

说明

golang stopcpuprofile示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: runtime/pprof

示例#1
文件: backend.go 项目: andreas-jonsson/octatron

func main() {
	flag.Parse()

	if arguments.pprof {
		log.Println("pprof enabled")
		go func() {
			log.Println(http.ListenAndServe("localhost:6060", nil))
		}()

		fp, err := os.Create("backend.pprof")
		if err != nil {
			panic(err)
		}
		defer fp.Close()

		pprof.StartCPUProfile(fp)
		defer pprof.StopCPUProfile()
	}

	if err := loadTree(arguments.tree); err != nil {
		log.Println(err)
		os.Exit(-1)
	}

	http.Handle("/", http.FileServer(http.Dir(arguments.web)))
	http.Handle("/render", websocket.Handler(renderServer))

	log.Println("waiting for connections...")
	if err := http.ListenAndServe(fmt.Sprintf(":%v", arguments.port), nil); err != nil {
		log.Println(err)
		os.Exit(-1)
	}
}

示例#2
文件: eventsrv.go 项目: vsysoev/goeventstore

func main() {
	f, err := os.Create("currentsrv.prof")
	if err != nil {
		log.Fatal(err)
	}
	pprof.StartCPUProfile(f)
	defer pprof.StopCPUProfile()
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	go func() {
		select {
		case <-c:
			log.Println("Stop profiling")
			pprof.StopCPUProfile()
			syscall.Exit(0)
		}
	}()

	props := property.Init()
	evStore, err := evstore.Dial(props["mongodb.url"], props["mongodb.db"], props["mongodb.stream"])
	if err != nil {
		log.Fatalln("Error connecting to event store. ", err)
	}
	wsServer := wsock.NewServer(props["events.uri"])
	if wsServer == nil {
		log.Fatalln("Error creating new websocket server")
	}
	go processClientConnection(wsServer, evStore)
	go wsServer.Listen()

	//http.Handle(props["static.url"], http.FileServer(http.Dir("webroot")))
	err = http.ListenAndServe(props["events.url"], nil)
	evStore.Close()
}

示例#3
文件: main.go 项目: postfix/bufferManager.go

func main() {
	list_T := make([]*buffered.Token, M)
	list_D := make([]*buffered.Data, M)
	t := time.Now()
	f, _ := os.Create("with_bufferManager.prof")
	pprof.StartCPUProfile(f)
	m := buffered.NewBufferManager(M * 2)
	for i := 0; i < N; i++ {
		for j := 0; j < M; j++ {
			t := m.GetToken()
			t.Data.Str = "haha"
			list_T[j] = t
		}
		for j := 0; j < M; j++ {
			list_T[j].Return()
		}
	}
	fmt.Printf("With bufferManager:                    %v\n", time.Since(t))
	pprof.StopCPUProfile()

	t = time.Now()
	f, _ = os.Create("without_bufferManager.prof")
	pprof.StartCPUProfile(f)
	for i := 0; i < N; i++ {
		for j := 0; j < M; j++ {
			d := new(buffered.Data)
			d.Str = "haha"
			list_D[j] = d
		}
	}
	fmt.Printf("Without buffermanager (Relying on GC): %v\n", time.Since(t))
	pprof.StopCPUProfile()

}

示例#4
文件: cmd.go 项目: timtadh/sfp

func CPUProfile(cpuProfile string) func() {
	errors.Logf("DEBUG", "starting cpu profile: %v", cpuProfile)
	f, err := os.Create(cpuProfile)
	if err != nil {
		log.Fatal(err)
	}
	err = pprof.StartCPUProfile(f)
	if err != nil {
		log.Fatal(err)
	}
	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
	go func() {
		sig := <-sigs
		errors.Logf("DEBUG", "closing cpu profile")
		pprof.StopCPUProfile()
		err := f.Close()
		errors.Logf("DEBUG", "closed cpu profile, err: %v", err)
		panic(errors.Errorf("caught signal: %v", sig))
	}()
	return func() {
		errors.Logf("DEBUG", "closing cpu profile")
		pprof.StopCPUProfile()
		err := f.Close()
		errors.Logf("DEBUG", "closed cpu profile, err: %v", err)
	}
}

示例#5
文件: service.go 项目: johntdyer/golang-devops-stuff

// This is a blocking call, starts reverse proxy, connects to the backends, etc
func (s *Service) Start() error {
	if s.options.cpuProfile != "" {
		f, err := os.Create(s.options.cpuProfile)
		if err != nil {
			return err
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()

		c := make(chan os.Signal, 1)
		signal.Notify(c, os.Interrupt)
		go func() {
			for sig := range c {
				glog.Errorf("captured %v, stopping profiler and exiting..", sig)
				pprof.StopCPUProfile()
				os.Exit(1)
			}
		}()
	}

	if err := s.writePid(); err != nil {
		return err
	}
	if err := s.startLogsCleanup(); err != nil {
		return err
	}

	proxy, err := s.initProxy()
	if err != nil {
		return err
	}
	s.proxy = proxy
	return s.startProxy()
}

示例#6
文件: main.go 项目: leobcn/gosnippet

func main() {
	// Use as many procs as there are
	runtime.GOMAXPROCS(runtime.NumCPU())

	// Enable CPU profiling if the flag is set
	// -cpuprofile=logfile.log
	flag.Parse()
	if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()

		// Catch CTRL+C and stop the profiling
		c := make(chan os.Signal, 1)
		signal.Notify(c, os.Interrupt)
		go func() {
			for sig := range c {
				log.Printf("captured %v, stopping profiler and exiting..", sig)
				pprof.StopCPUProfile()
				os.Exit(1)
			}
		}()
	}

	server.StartServer()
}

示例#7
文件: main.go 项目: dylanpoe/decrypt-symmetric

func main() {
	flag.Parse()

	if cpuprofile != "" {
		profFD, err := os.Create(cpuprofile)
		if err != nil {
			log.Fatalf("Cpuprofile: os.Create(): %v", err)
		}

		pprof.StartCPUProfile(profFD)
		defer pprof.StopCPUProfile()
	}

	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP,
		syscall.SIGPIPE)
	go func() {
		<-c

		if cpuprofile != "" {
			pprof.StopCPUProfile()
		}

		// In case we had a hang, we print the stack trace here.
		buf := make([]byte, 256*1024)
		n := runtime.Stack(buf, true)
		fmt.Fprintln(os.Stderr, string(buf[0:n]))

		os.Exit(1)
	}()

	var fd *os.File = os.Stdin
	var err error
	if filename != "" {
		fd, err = os.Open(filename)
		if err != nil {
			log.Fatalf("Input: os.Open(): %v", err)
		}
		defer fd.Close()
	}

	md, err := openpgp.ReadMessage(fd, emptyKR{}, newPromptFunction(), nil)
	if err != nil {
		log.Fatalf("openpgp.ReadMessage(): %v", err)
	}
	log.Println("openpgp.ReadMessage() returned without error")

	_, err = io.Copy(os.Stdout, md.UnverifiedBody)
	if err != nil {
		log.Fatalf("Reading unverified plain text: io.Copy(): %v", err)
	}

	// Check that any authentication code for the message was
	// verified successfully
	if md.SignatureError != nil {
		log.Fatalln("Integrity Check FAILED:", md.SignatureError)
	}
}

示例#8
文件: master.go 项目: ham1/seaweedfs

func runMaster(cmd *Command, args []string) bool {
	if *mMaxCpu < 1 {
		*mMaxCpu = runtime.NumCPU()
	}
	runtime.GOMAXPROCS(*mMaxCpu)
	if *masterCpuProfile != "" {
		f, err := os.Create(*masterCpuProfile)
		if err != nil {
			glog.Fatal(err)
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
		OnInterrupt(func() {
			pprof.StopCPUProfile()
		})
	}
	if err := util.TestFolderWritable(*metaFolder); err != nil {
		glog.Fatalf("Check Meta Folder (-mdir) Writable %s : %s", *metaFolder, err)
	}
	if *masterWhiteListOption != "" {
		masterWhiteList = strings.Split(*masterWhiteListOption, ",")
	}

	r := mux.NewRouter()
	ms := weed_server.NewMasterServer(r, *mport, *metaFolder,
		*volumeSizeLimitMB, *mpulse, *confFile, *defaultReplicaPlacement, *garbageThreshold,
		masterWhiteList, *masterSecureKey,
	)

	listeningAddress := *masterBindIp + ":" + strconv.Itoa(*mport)

	glog.V(0).Infoln("Start Seaweed Master", util.VERSION, "at", listeningAddress)

	listener, e := util.NewListener(listeningAddress, time.Duration(*mTimeout)*time.Second)
	if e != nil {
		glog.Fatalf("Master startup error: %v", e)
	}

	go func() {
		time.Sleep(100 * time.Millisecond)
		myMasterAddress := *masterIp + ":" + strconv.Itoa(*mport)
		var peers []string
		if *masterPeers != "" {
			peers = strings.Split(*masterPeers, ",")
		}
		raftServer := weed_server.NewRaftServer(r, peers, myMasterAddress, *metaFolder, ms.Topo, *mpulse)
		ms.SetRaftServer(raftServer)
	}()

	if e := http.Serve(listener, r); e != nil {
		glog.Fatalf("Fail to serve: %v", e)
	}
	return true
}

示例#9
文件: log.go 项目: yunkaiyueming/go_code

func SavePprofShot() {
	f, err := os.OpenFile("E:/GO_PATH/src/go_code/cpu.prof", os.O_RDWR|os.O_CREATE, 0644)
	if err != nil {
		log.Fatal(err)
	}

	defer f.Close()
	pprof.StartCPUProfile(f)
	defer pprof.StopCPUProfile()

	pprof.StopCPUProfile()
	f.Close()
}

示例#10
文件: main.go 项目: pquerna/hurl

func main() {

	if os.Getenv("GOMAXPROCS") == "" {
		runtime.GOMAXPROCS(runtime.NumCPU())
	}

	cmd := &cobra.Command{
		Use:   "hurl",
		Short: "hurl is a tool to hurl traffic at URLs",
		Long: `hurl is a flexiable benchmarking tool with the ability to scale out.

Complete documentation is available online at:
	https://github.com/pquerna/hurl/`,
		Run: func(cmd *cobra.Command, args []string) {
			cmd.UsageFunc()(cmd)
		},
	}

	cpuprofile := os.Getenv("CPUPROFILE")

	if cpuprofile != "" {
		f, err := os.Create(cpuprofile)
		if err != nil {
			fmt.Errorf("Error opening: %s, %v\n", cpuprofile, err)
			panic(err)
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()

		c := make(chan os.Signal, 1)
		signal.Notify(c, os.Interrupt)
		go func() {
			for sig := range c {
				fmt.Printf("captured %v, stopping profiler and exiting..", sig)
				pprof.StopCPUProfile()
				os.Exit(1)
			}
		}()
	}

	subcmds := ui.ConsoleCommands()

	for _, c := range subcmds {
		cmd.AddCommand(c)
	}

	err := cmd.Execute()
	if err != nil {
		common.ConsoleErr(cmd, fmt.Sprintf("Error: %s", err))
	}
}

示例#11
文件: gopush_server.go 项目: Pronovix/gopush

func main() {
	flag.Parse()

	if *procs == 0 {
		runtime.GOMAXPROCS(runtime.NumCPU())
	} else {
		runtime.GOMAXPROCS(*procs)
	}

	if *logFile != "" {
		f, err := os.OpenFile(*logFile, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666)
		if err != nil {
			log.Fatalln(err.Error())
		}
		log.SetOutput(f)
	}

	if *cpuProfile != "" {
		f, err := os.Create(*cpuProfile)
		if err != nil {
			log.Fatalln(err.Error())
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}

	config, err := gopush.ReadConfig(*configName)
	if err != nil {
		log.Fatal(err)
	}

	svc := gopush.NewService(config, gopush.NewMySQLBackend(config), gopush.NewStandardTemplateStoreInWorkingDir())

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	go func() {
		for sig := range c {
			svc.Stop()
			log.Printf("Received signal %d, shutting down\n", sig)
			if *cpuProfile != "" { // Stop profiling
				pprof.StopCPUProfile()
			}
			os.Exit(1)
		}
	}()

	if err := svc.Start(); err != nil {
		log.Fatal(err)
	}
}

示例#12
文件: projecteuler.go 项目: herumi/misc

func prob41() {
	f, _ := os.Create("a.prof")
	pprof.StartCPUProfile(f)
	defer pprof.StopCPUProfile()
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	go func() {
		s := <-c
		switch s {
		case syscall.SIGINT:
			pprof.StopCPUProfile()
			os.Exit(1)
		}
	}()

	mk := func(n int) []int {
		v := make([]int, n)
		for i := 0; i < n; i++ {
			v[i] = -(n - i)
		}
		return v
	}
	toI := func(v []int) int {
		r := 0
		for _, x := range v {
			r = r*10 + x
		}
		return -r
	}
	// 1+...+9 = 45 = 0 mod 3
	// 1+...+8 = 36 = 0 mod 3
	// so, you can start with n := 7
	n := 9
	v := mk(n)
	for {
		p := toI(v)
		if v[len(v)-1]%2 != 0 && IsPrime(p) {
			fmt.Println(p)
			break
		}
		b := NextPermutation(v)
		if !b {
			n--
			if n == 1 {
				break
			}
			v = mk(n)
		}
	}
}

示例#13
文件: saxer.go 项目: tcw/saxer

func main() {
	kingpin.Version("0.0.7")
	kingpin.Parse()

	//go tool pprof --pdf saxer cpu.pprof > callgraph.pdf
	//evince callgraph.pdf

	if *cpuProfile {
		f, err := os.Create("cpu.pprof")
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
		fmt.Println("profiling!")
		defer pprof.StopCPUProfile()
	}

	if strings.TrimSpace(*filename) != "" {
		absFilename, err := abs(*filename)
		if err != nil {
			fmt.Printf("Error finding file: %s\n", absFilename)
		}
		file, err := os.Open(absFilename)
		if err != nil {
			fmt.Printf("Error opening file: %s\n", absFilename)
		}
		defer file.Close()
		SaxXmlInput(file)
	} else {
		reader := bufio.NewReader(os.Stdin)
		SaxXmlInput(reader)
	}
}

示例#14
文件: goprofile.go 项目: elivoa/gotapestry

func test() {

	f, _ := os.Create("ls.prof")

	flag.Parse()
	if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
		defer func() {
			pprof.StopCPUProfile()
		}()
	}

	// ...
	t := &T{}
	for i := 0; i < 1000000; i++ {
		v := reflect.ValueOf(t)
		if v.Kind() == reflect.Ptr {
			v = v.Elem()
		}
		t.B = append(t.B, i)
		t.A = append(t.A, sumtest())
	}

	// var buffer bytes.Buffer
	pprof.WriteHeapProfile(f)
	// fmt.Println(buffer.String())

}

示例#15
文件: main.go 项目: cdshann/minimega

func teardown() {
	// Clear namespace so that we hit all the VMs
	SetNamespace("")

	vncClear()
	clearAllCaptures()
	vms.Kill(Wildcard)
	dnsmasqKillAll()
	ksmDisable()
	vms.Flush()
	vms.CleanDirs()
	containerTeardown()

	if err := bridgesDestroy(); err != nil {
		log.Errorln(err)
	}

	commandSocketRemove()
	goreadline.Rlcleanup()

	if err := os.Remove(filepath.Join(*f_base, "minimega.pid")); err != nil {
		log.Fatalln(err)
	}

	if cpuProfileOut != nil {
		pprof.StopCPUProfile()
		cpuProfileOut.Close()
	}

	os.Exit(0)
}

示例#16
文件: cpuprofile.go 项目: bssthu/gitlab-ci-multi-runner

func SetupCPUProfile(app *cli.App) {
	app.Flags = append(app.Flags, cli.StringFlag{
		Name:   "cpuprofile",
		Usage:  "write cpu profile to file",
		EnvVar: "CPU_PROFILE",
	})

	appBefore := app.Before
	appAfter := app.After

	app.Before = func(c *cli.Context) error {
		if cpuProfile := c.String("cpuprofile"); cpuProfile != "" {
			f, err := os.Create(cpuProfile)
			if err != nil {
				return err
			}
			pprof.StartCPUProfile(f)
		}

		if appBefore != nil {
			return appBefore(c)
		}
		return nil
	}

	app.After = func(c *cli.Context) error {
		pprof.StopCPUProfile()

		if appAfter != nil {
			return appAfter(c)
		}
		return nil
	}
}

示例#17
文件: benchtools.go 项目: jmptrader/encoding

func RunCompress(codec encoding.Integer, in []int32, length int, prof bool) (duration int64, out []int32, err error) {
	out = make([]int32, length*2)
	inpos := cursor.New()
	outpos := cursor.New()

	now := time.Now()
	if prof {
		f, e := os.Create("cpu.compress.pprof")
		if e != nil {
			log.Fatal(e)
		}
		defer f.Close()

		pprof.StartCPUProfile(f)
	}

	if err = codec.Compress(in, inpos, len(in), out, outpos); err != nil {
		return 0, nil, err
	}
	since := time.Since(now).Nanoseconds()

	if prof {
		pprof.StopCPUProfile()
	}

	return since, out[:outpos.Get()], nil
}

示例#18
文件: profile.go 项目: rhino1998/god

func main() {
	f, err := os.Create("cpuprofile")
	if err != nil {
		panic(err.Error())
	}
	f2, err := os.Create("memprofile")
	if err != nil {
		panic(err.Error())
	}

	pprof.StartCPUProfile(f)
	defer pprof.StopCPUProfile()
	defer pprof.WriteHeapProfile(f2)

	m := radix.NewTree()
	var k []byte
	for i := 0; i < 100000; i++ {
		k = murmur.HashString(fmt.Sprint(i))
		m.Put(k, k, 1)
		x, _, _ := m.Get(k)
		if bytes.Compare(x, k) != 0 {
			panic("humbug")
		}
	}
}

示例#19
文件: loadbalancer.go 项目: jyzhe/beehive-netctrl

func main() {
	flag.Parse()
	if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}

	h := bh.NewHive()
	openflow.StartOpenFlow(h)
	controller.RegisterNOMController(h)
	discovery.RegisterDiscovery(h)

	// Register a switch:
	// switching.RegisterSwitch(h, bh.Persistent(1))
	// or a hub:
	// switching.RegisterHub(h, bh.NonTransactional())

	// routing.InstallRouter(h, bh.Persistent(1))
	routing.InstallLoadBalancer(h, bh.Persistent(1))
	h.Start()
}

示例#20
文件: lrutest.go 项目: NZWDDY/jgc-talks

func main() {
	f, _ := os.Create("lrutest.cpuprofile")
	pprof.StartCPUProfile(f)
	defer pprof.StopCPUProfile()

	cache := lru1.NewCache(1000)

	count := 0
	miss := 0

	in := bufio.NewScanner(os.Stdin)
	for in.Scan() {
		f := strings.Split(in.Text(), "|")
		if len(f) > 2 {
			email := strings.Split(f[2], "@")
			if len(email) > 1 {
				domain := email[1]

				if i := cache.Get(domain); i == nil {
					cache.Put(domain, f[2])
					miss += 1
				}

				count += 1
			}
		}
	}

	fmt.Printf("%d total %d misses\n", count, miss)
}

示例#21
文件: benchmark.go 项目: maruel/hugo

func bench(cmd *cobra.Command, args []string) {

	if memProfilefile != "" {
		f, err := os.Create(memProfilefile)

		if err != nil {
			panic(err)
		}
		for i := 0; i < benchmarkTimes; i++ {
			_ = buildSite()
		}
		pprof.WriteHeapProfile(f)
		f.Close()

	} else {
		if cpuProfilefile == "" {
			cpuProfilefile = "/tmp/hugo-cpuprofile"
		}
		f, err := os.Create(cpuProfilefile)

		if err != nil {
			panic(err)
		}

		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
		for i := 0; i < benchmarkTimes; i++ {
			_ = buildSite()
		}
	}

}

示例#22
文件: main.go 项目: gulinfang/GarageEngine

func main() {
	runtime.GOMAXPROCS(8)
	flag.Parse()
	if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		if err != nil {
			fmt.Errorf("%s\n", err)
		}
		pprof.StartCPUProfile(f)

		defer pprof.StopCPUProfile()
	}

	file, _ := os.Create("./log.txt")
	os.Stdout = file
	os.Stderr = file
	os.Stdin = file
	defer file.Close()

	Start()

	if *memprofile != "" {
		f, err := os.Create(*memprofile)
		if err != nil {
			fmt.Errorf("%s\n", err)
		}
		pprof.WriteHeapProfile(f)
		f.Close()
		return
	}
}

示例#23
文件: util.go 项目: Comcast/rulio

// Profile starts CPU and memory profiling and returns a function that will stop that.
//
//
// Writes "cpu" + filename and "mem" + filename.
//
// Usage:
//
//   defer Profile("logfast.prof")()
//
func Profile(filename string) func() {
	cpu, err := os.Create("cpu" + filename)
	if err != nil {
		panic(err)
	}

	mem, err := os.Create("mem" + filename)
	if err != nil {
		panic(err)
	}

	then := time.Now()
	log.Printf("Profile starting %s\n", filename)
	pprof.StartCPUProfile(cpu)
	pprof.WriteHeapProfile(mem)

	return func() {
		elapsed := time.Now().Sub(then)
		log.Printf("Profile stopping %s (elapsed %v)\n", filename, elapsed)
		pprof.StopCPUProfile()
		if err := mem.Close(); err != nil {
			log.Printf("error closing mem profile (%v)", err)
		}
	}
}

示例#24
文件: main.go 项目: jsfr/SteinerExact

func main() {
	c := initConfig()

	offset := 0
	if c.Offset {
		offset = 1
	}

	if c.CPUProfile != "" {
		f, err := os.Create(c.CPUProfile)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}

	if c.SortPoints {
		c.Points.SortPoints()
	}

	t := smt.InitTree(&c.Points)

	optimize(t, offset, c.Iteration)
}

示例#25
文件: cmd.go 项目: marcopaganini/rclone

// initConfig is run by cobra after initialising the flags
func initConfig() {
	// Log file output
	if *logFile != "" {
		f, err := os.OpenFile(*logFile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0640)
		if err != nil {
			log.Fatalf("Failed to open log file: %v", err)
		}
		_, err = f.Seek(0, os.SEEK_END)
		if err != nil {
			fs.ErrorLog(nil, "Failed to seek log file to end: %v", err)
		}
		log.SetOutput(f)
		fs.DebugLogger.SetOutput(f)
		redirectStderr(f)
	}

	// Load the rest of the config now we have started the logger
	fs.LoadConfig()

	// Write the args for debug purposes
	fs.Debug("rclone", "Version %q starting with parameters %q", fs.Version, os.Args)

	// Setup CPU profiling if desired
	if *cpuProfile != "" {
		fs.Log(nil, "Creating CPU profile %q\n", *cpuProfile)
		f, err := os.Create(*cpuProfile)
		if err != nil {
			fs.Stats.Error()
			log.Fatal(err)
		}
		err = pprof.StartCPUProfile(f)
		if err != nil {
			fs.Stats.Error()
			log.Fatal(err)
		}
		defer pprof.StopCPUProfile()
	}

	// Setup memory profiling if desired
	if *memProfile != "" {
		defer func() {
			fs.Log(nil, "Saving Memory profile %q\n", *memProfile)
			f, err := os.Create(*memProfile)
			if err != nil {
				fs.Stats.Error()
				log.Fatal(err)
			}
			err = pprof.WriteHeapProfile(f)
			if err != nil {
				fs.Stats.Error()
				log.Fatal(err)
			}
			err = f.Close()
			if err != nil {
				fs.Stats.Error()
				log.Fatal(err)
			}
		}()
	}
}

示例#26
文件: command.go 项目: freeznet/leaf

func (c *CommandCPUProf) run(args []string) string {
	if len(args) == 0 {
		return c.usage()
	}

	switch args[0] {
	case "start":
		fn := profileName() + ".cpuprof"
		f, err := os.Create(fn)
		if err != nil {
			return err.Error()
		}
		err = pprof.StartCPUProfile(f)
		if err != nil {
			f.Close()
			return err.Error()
		}
		return fn
	case "stop":
		pprof.StopCPUProfile()
		return ""
	default:
		return c.usage()
	}
}

示例#27
文件: pr003.go 项目: d3zd3z/euler

func omain() {
	f, err := os.Create("profile.out")
	if err != nil {
		log.Fatal("Cannot create profile")
	}
	pprof.StartCPUProfile(f)
	defer pprof.StopCPUProfile()

	var sieve euler.SieveHeap

	num := start
	for {
		prime := sieve.Next()
		if num == prime {
			fmt.Printf("%d\n", prime)
			break
		}

		// Divide out the prime as many times as possible.
		for num%prime == 0 {
			num /= prime
		}
	}

	// for i := 0; i < 100; i++ {
	// 	fmt.Printf("%8d\n", sieve.Next())
	// }
	bench()
}

示例#28
文件: square1.go 项目: exupero/square1

func main() {
	flag.Parse()
	needed := requirements()

	if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}

	for steps := range square1.Sequences(square1.PossibleMoves) {
		if square1.Satisfies(needed, steps) {
			names := []string{}
			move := steps
			for {
				names = append(names, move.Name)
				if move.Next != nil {
					move = move.Next
				} else {
					break
				}
			}
			fmt.Println(names)
			return
		}
	}
}

示例#29
文件: pprofile.go 项目: NetSys/quilt

// Stop profiling and output results to a file. Also dump a memory profile.
func (pro *Prof) Stop() error {
	pprof.StopCPUProfile()
	pro.fd.Close()

	profileDir := "Profile-" + time.Now().Format("Jan_02_2006-15.04.05")
	if err := os.Mkdir(profileDir, 0777); err != nil {
		return err
	}

	cpuProfilePath := filepath.Join(profileDir, pro.fname)
	if err := os.Rename(pro.fname+".tmp", cpuProfilePath); err != nil {
		return fmt.Errorf("failed to rename tmp file: %s", err)
	}

	memProfilePath := filepath.Join(profileDir, pro.fname+".mem")
	memFile, err := os.Create(memProfilePath)
	if err != nil {
		return fmt.Errorf("failed to create mem file: %s", err)
	}
	defer memFile.Close()

	runtime.GC()
	if err := pprof.WriteHeapProfile(memFile); err != nil {
		return fmt.Errorf("failed to write heap profile: %s", err)
	}
	return nil
}

示例#30
文件: surgemq.go 项目: XcoderAlex/surgemq

func main() {
	svr := &service.Server{
		KeepAlive:        keepAlive,
		ConnectTimeout:   connectTimeout,
		AckTimeout:       ackTimeout,
		TimeoutRetries:   timeoutRetries,
		SessionsProvider: sessionsProvider,
		TopicsProvider:   topicsProvider,
	}

	var f *os.File
	var err error

	if cpuprofile != "" {
		f, err = os.Create(cpuprofile)
		if err != nil {
			log.Fatal(err)
		}

		pprof.StartCPUProfile(f)
	}

	sigchan := make(chan os.Signal, 1)
	signal.Notify(sigchan, os.Interrupt, os.Kill)
	go func() {
		sig := <-sigchan
		glog.Errorf("Existing due to trapped signal; %v", sig)

		if f != nil {
			glog.Errorf("Stopping profile")
			pprof.StopCPUProfile()
			f.Close()
		}

		svr.Close()

		os.Exit(0)
	}()

	mqttaddr := "tcp://:1883"

	if len(wsAddr) > 0 || len(wssAddr) > 0 {
		addr := "tcp://127.0.0.1:1883"
		AddWebsocketHandler("/mqtt", addr)
		/* start a plain websocket listener */
		if len(wsAddr) > 0 {
			go ListenAndServeWebsocket(wsAddr)
		}
		/* start a secure websocket listener */
		if len(wssAddr) > 0 && len(wssCertPath) > 0 && len(wssKeyPath) > 0 {
			go ListenAndServeWebsocketSecure(wssAddr, wssCertPath, wssKeyPath)
		}
	}

	/* create plain MQTT listener */
	err = svr.ListenAndServe(mqttaddr)
	if err != nil {
		glog.Errorf("surgemq/main: %v", err)
	}
}

展开阅读全文