问题似乎来自您对的使用
rand.Float64(),它使用了一个共享全局对象并带有Mutex锁。
相反,如果为每个CPU创建一个单独的
rand.New(),将其传递到
interactions(),然后使用它来创建
Float64(),则会有很大的改进。
更新以显示对现在使用的问题中新示例代码的更改rand.New()
该
test()函数已修改为使用给定通道或返回结果。
func test(n int, c chan []int) []int { source := rand.NewSource(time.Now().UnixNano()) generator := rand.New(source) simulations := make([]int, n) for i := range simulations { for _, v := range simulation(NUMBER_OF_INTERACTIONS, generator) { simulations[i] += v } } if c == nil { return simulations } c <- simulations return nil }该
main()功能已更新为可以运行两个测试,并输出定时结果。
func main() { rand.Seed(time.Now().UnixNano()) nCPU := runtime.NumCPU() runtime.GOMAXPROCS(nCPU) fmt.Println("Number of CPUs: ", nCPU) start := time.Now() fmt.Println("Successful interactions: ", len(test(NUMBER_OF_SIMULATIONS, nil))) fmt.Println(time.Since(start)) start = time.Now() tests := make([]chan []int, nCPU) for i := range tests { c := make(chan []int) go test(NUMBER_OF_SIMULATIONS/nCPU, c) tests[i] = c } // Concatentate the test results results := make([]int, NUMBER_OF_SIMULATIONS) for i, c := range tests { start := (NUMBER_OF_SIMULATIONS/nCPU) * i stop := (NUMBER_OF_SIMULATIONS/nCPU) * (i+1) copy(results[start:stop], <-c) } fmt.Println("Successful interactions: ", len(results)) fmt.Println(time.Since(start))}输出是我收到的:
> CPU数量:2 >>成功的互动:1000 > 1分20.39959秒>>成功的互动:1000> 41.392299s



