Last active
January 7, 2018 22:57
-
-
Save tidwall/ffb1c10bea9ed670cffed0c1e2284608 to your computer and use it in GitHub Desktop.
go performance for multi core machines
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
package main | |
import ( | |
"flag" | |
"fmt" | |
"math/rand" | |
"runtime" | |
"sync" | |
"sync/atomic" | |
"time" | |
) | |
func main() { | |
var threads int | |
var N int | |
flag.IntVar(&threads, "t", 0, "number of threads, 0 = host cpus") | |
flag.IntVar(&N, "n", 10000000000, "number of ops per thread") | |
flag.Parse() | |
if threads <= 0 { | |
threads = runtime.NumCPU() | |
} | |
var f int64 | |
var wg sync.WaitGroup | |
wg.Add(threads) | |
rand.Seed(time.Now().UnixNano()) | |
start := time.Now() | |
for i := 0; i < threads; i++ { | |
go func(r, n int) { | |
var t int | |
for j := 0; j < n; j++ { | |
t += r * j | |
} | |
atomic.AddInt64(&f, int64(t)) | |
wg.Done() | |
}(rand.Int(), N) | |
} | |
wg.Wait() | |
dur := time.Since(start) | |
fmt.Printf("%s ops over %s threads in %s (%s ops/sec)\n", | |
commaize(N*threads), commaize(threads), dur, commaize(int(float64(N*threads)/dur.Seconds()))) | |
} | |
func commaize(n int) string { | |
nstr1, nstr := fmt.Sprintf("%d", n), "" | |
for i, j := len(nstr1)-1, 0; i >= 0; i, j = i-1, j+1 { | |
nstr = string(nstr1[i]) + nstr | |
if i != 0 && j%3 == 2 { | |
nstr = "," + nstr | |
} | |
} | |
return nstr | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment