福哥答案2020-06-01:
fork/join。
对于百万级长度的数组求和,单线程和多线程下区别不大。
对于千万级长度的数组求和,多线程明显变快,大概是单线程的2-3倍。
go语言测试代码如下:
package test18_sum100w import ( "fmt" "math/rand" "testing" "time" ) const ( ARRLEN = 100_0000 ) var arr []int func init() { arr = make([]int, ARRLEN) rand.Seed(time.Now().UnixNano()) for i := 0; i < ARRLEN; i++ { arr[i] = rand.Intn(10_0000_0000) } fmt.Println("初始化完成") } func TestAA(t *testing.T) { } func TestMutiThreadsToSum(t *testing.T) { fmt.Println("多线程开始") now := time.Now() sum := 0 const MAXGE = 10000 const MAXHANG = 100 ch := make(chan int, MAXHANG) f := func(i int) { sumtemp := 0 for j := 0; j < MAXGE; j++ { sumtemp += arr[i*MAXGE+j] } ch <- sumtemp } for i := 0; i < MAXHANG; i++ { go f(i) } for i := 0; i < MAXHANG; i++ { sum += <-ch } fmt.Println(sum) fmt.Println("多线程结束", time.Now().Sub(now)) } //go test -v -test.run TestSingleThreadToSum //go test -bench=. -test.run TestSingleThreadToSum //go test -v -cover -run TestSingleThreadToSum func TestSingleThreadToSum(t *testing.T) { fmt.Println("单线程开始") now := time.Now() sum := 0 for i := 0; i < ARRLEN; i++ { sum += arr[i] } fmt.Println(sum) fmt.Println("单线程结束", time.Now().Sub(now)) }
敲命令go test -v:
改下代码,将100万数组改成1000万。测试结果如下:
ARRLEN = 1000_0000
const MAXHANG = 1000