Example #1
0
// StartCPUProfile enables CPU profiling for the current process.
// While profiling, the profile will be buffered and written to w.
// StartCPUProfile returns an error if profiling is already enabled.
func StartCPUProfile(w io.Writer) error {
	// The runtime routines allow a variable profiling rate,
	// but in practice operating systems cannot trigger signals
	// at more than about 500 Hz, and our processing of the
	// signal is not cheap (mostly getting the stack trace).
	// 100 Hz is a reasonable choice: it is frequent enough to
	// produce useful data, rare enough not to bog down the
	// system, and a nice round number to make it easy to
	// convert sample counts to seconds.  Instead of requiring
	// each client to specify the frequency, we hard code it.
	const hz = 100

	// Avoid queueing behind StopCPUProfile.
	// Could use TryLock instead if we had it.
	if cpu.profiling {
		return fmt.Errorf("cpu profiling already in use")
	}

	cpu.Lock()
	defer cpu.Unlock()
	if cpu.done == nil {
		cpu.done = make(chan bool)
	}
	// Double-check.
	if cpu.profiling {
		return fmt.Errorf("cpu profiling already in use")
	}
	cpu.profiling = true
	runtime.SetCPUProfileRate(hz)
	go profileWriter(w)
	return nil
}
Example #2
0
func waitForSignals(stoppable Stoppable, filename string, stopped <-chan bool) {
	ch := make(chan os.Signal)
	signal.Notify(ch, syscall.SIGTERM, syscall.SIGINT)
outer:
	for {
		sig := <-ch
		log.Info("Received signal: %s", sig.String())
		switch sig {
		case syscall.SIGINT, syscall.SIGTERM:
			runtime.SetCPUProfileRate(0)
			f, err := os.OpenFile(fmt.Sprintf("%s.mem", filename), os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0600)
			if err != nil {
				log.Error("Cannot open memory profile: %s", err)
				break outer
			}
			if err := pprof.WriteHeapProfile(f); err != nil {
				log.Error("Cannot write memory profile: %s", err)
			}
			f.Close()
			stopCHeapProfiler()
			// stopCCpuProfiler()
			stoppable.Stop()
			break outer
			// make sure everything stopped before exiting
		}
	}
	// wait for all logging messages to be printed
	<-stopped
	time.Sleep(5 * time.Second)
	os.Exit(0)
}
Example #3
0
func startProfiler(filename *string) error {
	if filename == nil || *filename == "" {
		return nil
	}

	cpuProfileFile, err := os.Create(*filename)
	if err != nil {
		return err
	}
	runtime.SetCPUProfileRate(500)
	stopped := make(chan bool)

	go waitForSignals(stopped)

	go func() {
		for {
			select {
			default:
				data := runtime.CPUProfile()
				if data == nil {
					cpuProfileFile.Close()
					stopped <- true
					break
				}
				cpuProfileFile.Write(data)
			}
		}
	}()
	return nil
}
Example #4
0
// StartCPUProfile 为当前进程开启CPU分析。
// 在分析时,分析报告会缓存并写入到 w 中。若分析已经开启,StartCPUProfile
// 就会返回错误。
func StartCPUProfile(w io.Writer) error {
	// The runtime routines allow a variable profiling rate,
	// but in practice operating systems cannot trigger signals
	// at more than about 500 Hz, and our processing of the
	// signal is not cheap (mostly getting the stack trace).
	// 100 Hz is a reasonable choice: it is frequent enough to
	// produce useful data, rare enough not to bog down the
	// system, and a nice round number to make it easy to
	// convert sample counts to seconds.  Instead of requiring
	// each client to specify the frequency, we hard code it.
	// 运行时例程允许可变的分析速率,但在实践中,操作系统并不能以超过500Hz
	// 的频率触发信号,而我们对信号的处理并不廉价(主要是获得栈跟踪信息)。
	// 100Hz是个不错的选择:此频率足以产生有用的信息,又不至于让系统瘫痪,
	// 而且这个不错的整数也能让采样计数转换成秒变得很容易。
	// 因此我们不会让每一个客户端都指定频率,而是将这一点作为硬性规定。
	const hz = 100

	cpu.Lock()
	defer cpu.Unlock()
	if cpu.done == nil {
		cpu.done = make(chan bool)
	}
	// Double-check.
	// 再次检查。
	if cpu.profiling {
		return fmt.Errorf("cpu profiling already in use")
	}
	cpu.profiling = true
	runtime.SetCPUProfileRate(hz)
	go profileWriter(w)
	return nil
}
Example #5
0
func startProfiler() error {
	if profileFilename == nil || *profileFilename == "" {
		return nil
	}

	startCHeapProfiler(*profileFilename)
	runtime.MemProfileRate = 1024

	cpuProfileFile, err := os.Create(fmt.Sprintf("%s.cpu", *profileFilename))
	if err != nil {
		return err
	}
	runtime.SetCPUProfileRate(500)
	stopped := make(chan bool)

	go waitForSignals(*profileFilename, stopped)

	go func() {
		for {
			select {
			default:
				data := runtime.CPUProfile()
				if data == nil {
					cpuProfileFile.Close()
					stopped <- true
					break
				}
				cpuProfileFile.Write(data)
			}
		}
	}()
	return nil
}
Example #6
0
// StopCPUProfile stops the current CPU profile, if any.
// StopCPUProfile only returns after all the writes for the
// profile have completed.
func StopCPUProfile() {
	cpu.Lock()
	defer cpu.Unlock()

	if !cpu.profiling {
		return
	}
	cpu.profiling = false
	runtime.SetCPUProfileRate(0)
	<-cpu.done
}
Example #7
0
func main() {

	fmt.Print("GOPROCS:=", runtime.GOMAXPROCS(6))
	runtime.SetCPUProfileRate(-1)
	start := time.Now()

	user1 := NewSetup()
	user2 := NewSetup()
	user3 := NewSetup()
	// user4 := NewSetup()
	// user5 := NewSetup()
	// fmt.Printf("\nLink %v", user1)
	// fmt.Printf("\nLink %v", user2)
	data, err := ioutil.ReadFile("settings.json")
	if err != nil {
		log.Print("Unable to Read File : ", err)
	}
	result := chipset.GetMetaInfo(data, "Modem1")
	fmt.Print("Found Setting : ", result, "len = ", len(result))
	var jsons string = `{"NBlocks":100,"snr":"0:2:16","SF":1}`
	var mymodem core.Modem
	mymodem.SetName("Modem2")
	mymodem.SetJson(data)

	fmt.Print("SOMETHING", string(mymodem.GetJson()))
	user1.Set(jsons)
	user2.Set(jsons)
	user3.Set(jsons)
	// user3.Set(jsons)
	// user4.Set(jsons)
	// user5.Set(jsons)
	fmt.Printf("Starting simulation ...")

	fmt.Printf("\n started user 1")
	go user1.Run()
	fmt.Printf("\n started user 2")
	go user2.Run()
	// go user3.Run()
	// go user4.Run()

	// 	user1.Run()
	// 	user2.Run()
	// 	user3.Run()
	// 	user4.Run()
	fmt.Printf("\n started user 3")
	user3.Run()

	// time.Sleep(10 * time.Second)
	fmt.Print("\n Elapsed : ", time.Since(start))

}
Example #8
0
func waitForSignals(stopped <-chan bool) {
	ch := make(chan os.Signal)
	signal.Notify(ch, syscall.SIGTERM, syscall.SIGINT)
	for {
		sig := <-ch
		log.Info("Received signal: %s\n", sig.String())
		switch sig {
		case syscall.SIGINT, syscall.SIGTERM:
			runtime.SetCPUProfileRate(0)
			<-stopped
			os.Exit(0)
		}
	}
}
Example #9
0
func startProfiler(stoppable Stoppable) error {
	if profileFilename == nil || *profileFilename == "" {
		log.Info("Not starting profiling since the profile prefix is not set")
		return nil
	}

	log.Info("Starting profiling with prefix %s", *profileFilename)

	startCHeapProfiler(*profileFilename)
	// startCCpuProfiler(*profileFilename)
	runtime.MemProfileRate = 1024

	cpuProfileFile, err := os.Create(fmt.Sprintf("%s.cpu", *profileFilename))
	if err != nil {
		return err
	}
	runtime.SetCPUProfileRate(500)
	stopped := make(chan bool)

	go waitForSignals(stoppable, *profileFilename, stopped)

	go func() {
		for {
			select {
			default:
				data := runtime.CPUProfile()
				if data == nil {
					cpuProfileFile.Close()
					stopped <- true
					break
				}
				cpuProfileFile.Write(data)
			}
		}
	}()
	return nil
}
Example #10
0
/*
*
* Main loops
*
 */
func main() {
	rand.Seed(time.Now().UTC().UnixNano())

	settings := &GameSettings{
		[2]string{"montecarlo", "negamax"},
		[2]float64{1, 9},
		X,
		false,
		false,
		NewMove(),
		new(Board),
	}

	prompt := flag.Bool("prompt", false, "Don't start game immediately.")
	ai_one := flag.Float64("s1", 2, "Set AI 1 strength.")
	ai_two := flag.Float64("s2", 2, "Set AI 2 strength.")

	player_one := flag.String("p1", "montecarlo", "Set player 1 to cpu or human.")
	player_two := flag.String("p2", "negamax", "Set player 2 to cpu or human.")
	var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")
	var memprofile = flag.String("memprofile", "", "write memory profile to file")

	flag.Parse()

	if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		if err != nil {
			log.Fatal(err)
			os.Exit(1)
		}
		runtime.SetCPUProfileRate(1000)
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}

	if !(*prompt) {
		settings.players[0] = *player_one
		settings.players[1] = *player_two
		settings.depth[0] = *ai_one
		settings.depth[1] = *ai_two
		settings.board = newBoard()
		settings.curplayer = X
		gameloop(settings)
		if *memprofile != "" {
			hf, err := os.Create(*memprofile)
			if err != nil {
				log.Fatal(err)
				os.Exit(1)
			}
			fmt.Println("Writing out heap profile")
			pprof.WriteHeapProfile(hf)
			hf.Close()
			return
		}
		os.Exit(0)
	}

	for {

		fmt.Printf(colourString("[uxobot]>"))
		var input, _ = Stdin.ReadString('\n')

		if strings.Contains(input, "help") {
			fmt.Println("Available commands are: start, quit")
		} else if strings.Contains(input, "quit") || strings.Contains(input, "exit") {
			os.Exit(0)
		} else if len(input) < 2 || strings.Contains(input, "start") && !settings.running {
			settings.board = newBoard()
			settings.curplayer = X
			gameloop(settings)
		} else {
			fmt.Println("Enter a valid command or type help.")
		}
	}

}
// CreateNode creates a new node, initializes all of its fields, and exposes its
// exported methods through RPC.
func CreateNode(conf Config, port string, address string) {
	// Register node as RPC server
	node := new(Node)
	rpc.Register(node)
	rpc.HandleHTTP()
	l, err := net.Listen("tcp", ":"+port)
	checkErr("listen error ", err)
	// Get port selected by server
	addrstr := l.Addr().String()
	colon := strings.LastIndex(addrstr, ":")
	port = addrstr[colon+1:]

	// Initialize Node fields
	node.Address = getIP() + ":" + port
	node.Port = port
	node.ID = GenID(node.Address)
	node.RPCListener = l
	node.Config = conf
	node.Members.init()
	node.initDB()
	node.rpcServ.Init()

	if conf.CPUProfile {
		go func() {
			log.Println(http.ListenAndServe("localhost:6060", nil))
		}()
	}

	if node.Config.FullKeys {
		fullKeys = true
	}

	// Join a ring if address is specified
	if address != "" {
		// We do not know the ID of the node connecting to, use stand-in
		var k Key
		broker := Peer{ID: k, Address: address}
		err = node.joinRing(&broker)
		if err != nil {
			log.Print("Failed to join ring: ", err)
			os.Exit(1)
		}
	} else { // Else make a new ring
		node.createRing()
	}
	var wg sync.WaitGroup
	wg.Add(1)
	go node.autoCheckPredecessor()
	go node.autoSyncMembers()
	go node.autoResolvePending()
	go node.sigHandler()

	if node.Config.CPUProfile {
		runtime.SetCPUProfileRate(10)
		runtime.SetBlockProfileRate(1)
		go func() {
			fmt.Println("starting server")
			log.Println(http.ListenAndServe("localhost:6060", nil))
		}()
	}

	fmt.Println(node.string())
	fmt.Println("Listening on port " + port)
	http.Serve(l, nil)
	// TODO: undo hackyness
	wg.Wait()
	return
}
Example #12
0
File: main.go Project: timtadh/sfp
func stopProfile() {
	runtime.SetCPUProfileRate(0)
	<-profileDone
}
Example #13
0
File: main.go Project: timtadh/sfp
func profileUnsafe(w io.Writer, hz int) {
	errors.Logf("DEBUG", "profileUnsafe at %v hz", hz)
	profileDone = make(chan bool)
	runtime.SetCPUProfileRate(hz)
	go profileWriter(w)
}