// Interface1 project Interface1.go
package main
import (
"log"
"runtime"
"sync"
"time"
)
const NCOUNT = 10000000001
var (
wg *sync.WaitGroup
)
func SubSum(b int, e int, idx int, SUM *[4]int) int {
var sum int
for i := b; i < e; i++ {
sum = sum + i
}
SUM[idx] = sum
wg.Done()
return sum
}
func SubSum2(b int, e int, idx int, SUM *[4]int) int {
var sum int
for i := b; i < e; i++ {
sum = sum + i
}
SUM[idx] = sum
return sum
}
func SubSum3(b int, e int, ch chan int) {
var sum int
for i := b; i < e; i++ {
sum = sum + i
}
ch <- sum
}
func ForRoute() {
log.Printf("=====普通模式============")
log.Println()
runtime.GOMAXPROCS(runtime.NumCPU())
CPUS := runtime.NumCPU()
N := NCOUNT / CPUS
MOD := NCOUNT % CPUS
log.Println(N, MOD)
t := time.Now()
var totalSum int
var SUMS [4]int
for j := 0; j < CPUS; j++ {
totalSum = totalSum + SubSum2(j*N, (j+1)*N, j, &SUMS)
}
if MOD > 0 {
for j := N * CPUS; j < NCOUNT; j++ {
totalSum = totalSum + j
}
}
log.Println(time.Since(t), totalSum)
}
func GoRoute() {
log.Printf("=====等待模式============")
log.Println()
runtime.GOMAXPROCS(runtime.NumCPU())
CPUS := runtime.NumCPU()
N := NCOUNT / CPUS
MOD := NCOUNT % CPUS
log.Println(N, MOD)
wg = &sync.WaitGroup{}
t := time.Now()
var totalSum int
var SUMS [4]int
wg.Add(CPUS)
for j := 0; j < CPUS; j++ {
go SubSum(j*N, (j+1)*N, j, &SUMS)
}
wg.Wait()
for j := 0; j < CPUS; j++ {
totalSum = totalSum + SUMS[j]
}
if MOD > 0 {
for j := N * CPUS; j < NCOUNT; j++ {
totalSum = totalSum + j
}
}
log.Println(time.Since(t), totalSum)
}
func GoRoute2() {
log.Printf("=====通道模式============")
log.Println()
runtime.GOMAXPROCS(runtime.NumCPU())
CPUS := runtime.NumCPU()
N := NCOUNT / CPUS
MOD := NCOUNT % CPUS
log.Println(N, MOD)
t := time.Now()
var totalSum int
chs := make([]chan int, 4)
for j := 0; j < CPUS; j++ {
chs[j] = make(chan int)
go SubSum3(j*N, (j+1)*N, chs[j])
}
for j := 0; j < CPUS; j++ {
t := <-chs[j]
totalSum = totalSum + t
}
if MOD > 0 {
for j := N * CPUS; j < NCOUNT; j++ {
totalSum = totalSum + j
}
}
log.Println(time.Since(t), totalSum)
}
func GoRoute3() {
log.Printf("=====通道模式2============")
log.Println()
runtime.GOMAXPROCS(runtime.NumCPU())
CPUS := runtime.NumCPU()
N := NCOUNT / CPUS
MOD := NCOUNT % CPUS
log.Println(N, MOD)
t := time.Now()
var totalSum int
chs := make(chan int, 4)
for j := 0; j < CPUS; j++ {
go SubSum3(j*N, (j+1)*N, chs)
}
for j := 0; j < CPUS; j++ {
t := <-chs
totalSum = totalSum + t
}
if MOD > 0 {
for j := N * CPUS; j < NCOUNT; j++ {
totalSum = totalSum + j
}
}
log.Println(time.Since(t), totalSum)
}
func main() {
GoRoute()
GoRoute2()
GoRoute3()
ForRoute()
}