本文整理汇总了Golang中runtime.NumCPU函数的典型用法代码示例。如果您正苦于以下问题:Golang NumCPU函数的具体用法?Golang NumCPU怎么用?Golang NumCPU使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NumCPU函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestChan3
func TestChan3() {
fmt.Println("@@@@@@@@@@@@ TestChan 3")
fmt.Printf("cpu num: %d\n", runtime.NumCPU()) // 8核cpu
// 虽然goroutine是并发执行的,但是它们并不是并行运行的。如果不告诉Go额外的东西,同
// 一时刻只会有一个goroutine执行。利用runtime.GOMAXPROCS(n)可以设置goroutine
// 并行执行的数量。GOMAXPROCS 设置了同时运行的CPU 的最大数量,并返回之前的设置。
val := runtime.GOMAXPROCS(runtime.NumCPU() * 4)
fmt.Printf("last goroutine num: %d\n", val) // 8个
fmt.Printf("goroutine num: %d\n", runtime.NumGoroutine()) // 4个goroutine同时运行
var ch1 chan int = make(chan int, 0)
var ch2 chan int = make(chan int, 0)
var ch3 chan int = make(chan int, 0)
go write(ch1, 22)
go write(ch2, 33)
go write(ch3, 44)
go read(ch1)
go read(ch2)
go read(ch3)
fmt.Printf("goroutine num: %d\n", runtime.NumGoroutine()) // 10个goroutine同时运行
sleep("TestChan3", 3)
}
示例2: main
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
fetchFeed()
e := echo.New()
e.Use(mw.Logger())
e.Use(mw.Recover())
e.Use(mw.StripTrailingSlash())
e.Use(mw.Gzip())
e.Use(cors.Default().Handler)
bundle, _ := ioutil.ReadFile("./build/bundle.js")
// stats
s := stats.New()
e.Use(s.Handler)
e.Get("/stats", func(c *echo.Context) error {
return c.JSON(http.StatusOK, s.Data())
})
// static files
e.Static("/public/css", "public/css")
e.Static("/universal.js", "./build/bundle.js")
e.Favicon("public/favicon.ico")
e.Get("/", selfjs.New(runtime.NumCPU(), string(bundle), rss))
e.Get("/about", selfjs.New(runtime.NumCPU(), string(bundle), loremJSON()))
e.Get("/api/data", apiFrontPage)
e.Get("/api/anotherpage", apiAnotherPage)
go tick()
fmt.Println("serving at port 3000")
e.Run(":3000")
}
示例3: main
func main() {
flag.Parse()
table := make(map[uint64]*big.Int)
keys := make(chan *rsa.PrivateKey)
go func() {
d := time.Tick(time.Minute)
for {
<-d
log.Printf("checked %v keypairs\n", len(table))
}
}()
runtime.GOMAXPROCS(runtime.NumCPU())
for i := 0; i < runtime.NumCPU(); i++ {
go generate(keys)
}
for {
priv := <-keys
check(table, priv.Primes[0])
check(table, priv.Primes[1])
}
}
示例4: main
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
maxRoutines := runtime.NumCPU()
products := make(chan int)
end := make(chan int)
numRoutines := 0
pandigital := 123456789
i := minBase
for {
for i <= maxBase && numRoutines <= maxRoutines {
i++
numRoutines++
go catenatedProductGenerator(i, products, end)
}
if i >= maxBase && numRoutines == 0 {
break
}
select {
case p := <-products:
if isPandigital(p) && p > pandigital {
pandigital = p
}
case <-end:
numRoutines--
}
}
fmt.Println(pandigital)
}
示例5: TestRunMonteCarlo
func TestRunMonteCarlo(t *testing.T) {
CPUS := runtime.NumCPU()
runtime.GOMAXPROCS(CPUS)
n := 1000000
workload := n / runtime.NumCPU()
results := make(chan int64, CPUS)
for c := 0; c < CPUS; c++ {
go func(c, size int) {
s := NewPercolationSimulator(size)
var value int64
for i := 0; i < workload; i++ {
value += s.Simulate() // sum of steps
}
results <- int64(value)
log.Printf("CPU %v returned steps %v out of workload %v", c, value, size*size*workload)
}(c, 5)
}
var total int64
for i := 0; i < CPUS; i++ {
total += <-results
}
log.Printf("ran %v simulations, got result %v", n, float64(total)/float64(25*n))
}
示例6: main
func main() {
commands := map[string]command{
"attack": attackCmd(),
"report": reportCmd(),
}
flag.Usage = func() {
fmt.Println("Usage: vegeta [globals] <command> [options]")
for name, cmd := range commands {
fmt.Printf("\n%s command:\n", name)
cmd.fs.PrintDefaults()
}
fmt.Printf("\nglobal flags:\n -cpus=%d Number of CPUs to use\n", runtime.NumCPU())
fmt.Println(examples)
}
cpus := flag.Int("cpus", runtime.NumCPU(), "Number of CPUs to use")
flag.Parse()
runtime.GOMAXPROCS(*cpus)
args := flag.Args()
if len(args) == 0 {
flag.Usage()
os.Exit(1)
}
if cmd, ok := commands[args[0]]; !ok {
log.Fatalf("Unknown command: %s", args[0])
} else if err := cmd.fn(args[1:]); err != nil {
log.Fatal(err)
}
}
示例7: main
func main() {
flag.Parse()
var err error
if db, err = sql.Open("mysql", connectionString); err != nil {
log.Fatalf("Error opening database: %s", err)
}
if err = db.Ping(); err != nil {
log.Fatalf("Cannot connect to db: %s", err)
}
dbConnCount := maxConnectionCount
if *prefork {
dbConnCount = (dbConnCount + runtime.NumCPU() - 1) / runtime.NumCPU()
}
db.SetMaxIdleConns(dbConnCount)
db.SetMaxOpenConns(dbConnCount * 2)
worldSelectStmt = mustPrepare(db, "SELECT id, randomNumber FROM World WHERE id = ?")
worldUpdateStmt = mustPrepare(db, "UPDATE World SET randomNumber = ? WHERE id = ?")
fortuneSelectStmt = mustPrepare(db, "SELECT id, message FROM Fortune")
s := &fasthttp.Server{
Handler: mainHandler,
Name: "fasthttp",
}
ln := getListener()
if err = s.Serve(ln); err != nil {
log.Fatalf("Error when serving incoming connections: %s", err)
}
}
示例8: main
func main() {
var defaultMaxprocs int
var err error
if defaultMaxprocs, err = strconv.Atoi(os.Getenv("GOMAXPROCS")); err != nil {
defaultMaxprocs = runtime.NumCPU() * 2
}
var mode, dir string
var port, maxprocs int
flag.StringVar(&mode, "mode", "", "[v1|v2|v3|bench|durable-bench|example]")
flag.StringVar(&dir, "dir", "", "database directory")
flag.IntVar(&port, "port", 0, "listening port number")
flag.IntVar(&maxprocs, "gomaxprocs", defaultMaxprocs, "GOMAXPROCS")
flag.Parse()
if mode == "" {
flag.PrintDefaults()
return
}
runtime.GOMAXPROCS(maxprocs)
log.Printf("GOMAXPROCS is set to %d", maxprocs)
if maxprocs < runtime.NumCPU() {
log.Printf("GOMAXPROCS (%d) is less than number of CPUs (%d), this may affect performance. You can change it via environment variable GOMAXPROCS or by passing CLI parameter -gomaxprocs", maxprocs, runtime.NumCPU())
}
switch mode {
case "v1":
fallthrough
case "v2":
fallthrough
case "v3":
if dir == "" {
log.Fatal("Please specify database directory, for example -dir=/tmp/db")
}
if port == 0 {
log.Fatal("Please specify port number, for example -port=8080")
}
db, err := db.OpenDB(dir)
if err != nil {
log.Fatal(err)
}
if mode == "v1" {
v1.Start(db, port)
} else if mode == "v2" {
v2.Start(db, port)
} else if mode == "v3" {
v3.Start(db, port)
}
case "bench":
benchmark()
case "durable-bench":
durableBenchmark()
case "example":
embeddedExample()
default:
flag.PrintDefaults()
return
}
}
示例9: main
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
f, _ := os.Create("./boqi.txt")
file = f
spider := sg.NewSpider("test", &MyProcess{})
downloader := sg.NewDownloader()
downloader.SetSleepTime(2 * time.Second)
downloader.SetRetryMaxCount(0)
downloader.RegisterMiddleware(mw.NewDefaultDownloaderMiddleware())
scheduler := sg.NewScheduler()
scheduler.SetUrlHeap(sg.NewUrlHeap(50))
scheduler.RegisterMiddleware(mw.NewDefaultSchedulerMiddleware())
pipeliner := sg.NewPipeliner()
pipeliner.RegisterMiddleware(mw.NewDefaultPipelinerMiddleware())
spider.SetThreadNum(runtime.NumCPU() * 2)
spider.SetDownloader(downloader)
spider.SetScheduler(scheduler)
spider.SetPipeliner(pipeliner)
spider.AddUrl("http://shop.boqii.com/")
//spider.AddUrl("http://www.epet.com/")
spider.SetTimeout(5 * time.Second)
spider.Run()
}
示例10: main
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
c := make(chan int, runtime.NumCPU())
stats := Stats{0, 0, 0, 0, 0, 0, 0}
nextNumber := int64(1000)
for i := int64(0); i < NUM_CLIENTS; i++ {
fmt.Println("Spawn inserter", i)
go simulate(i, &nextNumber, &stats, c)
}
// Wait for interrupt signal
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
<-sigs
// Print out statistics
fmt.Println()
fmt.Println("Write percentage: ", float64(stats.totalWrites)/float64(stats.totalWrites+stats.totalReads))
fmt.Println("Empty read percentage: ", float64(stats.emptyReads)/float64(stats.totalReads))
fmt.Println("Total documents read: ", stats.totalDocumentsRead)
fmt.Println("Total documents written: ", stats.totalInsertions)
fmt.Println("Total documents updated: ", stats.totalUpdates)
fmt.Println("Total documents deleted: ", stats.totalDeletions)
}
示例11: NewContext
func NewContext(requestId string, datastore, systemstore datastore.Datastore,
namespace string, readonly bool, maxParallelism int, namedArgs map[string]value.Value,
positionalArgs value.Values, credentials datastore.Credentials,
consistency datastore.ScanConsistency, vector timestamp.Vector, output Output) *Context {
rv := &Context{
requestId: requestId,
datastore: datastore,
systemstore: systemstore,
namespace: namespace,
readonly: readonly,
maxParallelism: maxParallelism,
now: time.Now(),
namedArgs: namedArgs,
positionalArgs: positionalArgs,
credentials: credentials,
consistency: consistency,
vector: vector,
output: output,
subplans: nil,
subresults: nil,
}
if rv.maxParallelism <= 0 || rv.maxParallelism > runtime.NumCPU() {
rv.maxParallelism = runtime.NumCPU()
}
return rv
}
示例12: Walk
func (w *Walker) Walk() fusefs.Tree {
wg := sync.WaitGroup{}
paths := make(chan string, runtime.NumCPU())
for i := 0; i < runtime.NumCPU(); i++ {
go worker(w, paths, &wg)
}
walker := fs.Walk(w.Path)
for walker.Step() {
if err := walker.Err(); err != nil {
continue
}
if walker.Stat().IsDir() {
continue
}
wg.Add(1)
paths <- walker.Path()
}
close(paths)
wg.Wait()
return w.tree
}
示例13: main
func main() {
in, err := ioutil.ReadAll(os.Stdin)
if err != nil {
log.Println(err, string(in))
}
difficulty := os.Args[1]
fmt.Fprintln(os.Stderr, "Called with difficulty:", difficulty)
quit := make(chan bool)
runtime.GOMAXPROCS(runtime.NumCPU())
cores := int64(runtime.NumCPU() * 2)
fmt.Fprintln(os.Stderr, "Running with", cores, "cores")
// var wg sync.WaitGroup
go gitCount()
// wg.Add(1)
for i := int64(0); i <= cores; i++ {
rand.Seed(time.Now().UnixNano() * i)
seed := rand.Intn(100000000000000)
go gitMoney(difficulty, in, quit, seed)
}
for {
select {
case <-quit:
return
}
}
// wg.Wait()
}
示例14: ParallelFor
func ParallelFor(n int, f func(p *P)) {
// TODO: this formula could probably be more clever
step := n / runtime.NumCPU() / 100
if step < 10 {
step = 10
}
gp := &GP{
max: int64(n),
current: 0,
step: int64(step),
}
gp.wg.Add(runtime.NumCPU())
for i := 0; i < runtime.NumCPU(); i++ {
go func() {
p := &P{
gp: gp,
}
f(p)
gp.wg.Done()
}()
}
gp.wg.Wait()
}
示例15: main
func main() {
args := flag.Args()
st, _ := os.Stdin.Stat()
if st.Mode()&os.ModeCharDevice == 0 {
args = append(args, "-")
}
if len(args) == 0 {
flag.Usage()
}
sema := newSema(runtime.NumCPU())
var wg sync.WaitGroup
wg.Add(len(args))
if !*checkArg {
printf("# seed %d", *seedArg)
if *use32 {
printf("# 32bit")
} else {
printf("# 64bit")
}
}
for _, fn := range args {
if *checkArg {
check(newSema(runtime.NumCPU()), fn)
} else {
sema.Run(func() { printHash(fn) })
}
}
sema.WaitAndClose()
if errored {
os.Exit(1)
}
}