Skip to content

Instantly share code, notes, and snippets.

@alexniver
Last active June 14, 2019 15:20
Show Gist options
  • Save alexniver/a7049fae1d0121e73f360e5fb98935c6 to your computer and use it in GitHub Desktop.
Save alexniver/a7049fae1d0121e73f360e5fb98935c6 to your computer and use it in GitHub Desktop.
calculate sum use all cpu core
package main
import (
"fmt"
"runtime"
)
func Sum(start, end int) chan int {
c := make(chan int)
s := 0
go func() {
for i := start; i <= end; i ++ {
s += i
}
c <- s
close(c)
}()
return c
}
func SumAll(n int) int {
cpuNum := runtime.GOMAXPROCS(0)
fmt.Printf("cpuNum : %+v\n", cpuNum)
step := n / cpuNum
if step == 0 {
cpuNum = n
step = 1
}
resChan := make(chan int)
for i := 0; i < cpuNum; i ++ {
go func(i int) {
start := i * step + 1
var end int
if i == cpuNum - 1 {
end = n
} else {
end = (i+1) * step
}
resChan <- <- Sum(start, end)
}(i)
}
result := 0
for i := 0; i < cpuNum; i ++ {
result += <-resChan
}
close(resChan)
return result
}
package main
import "testing"
func TestSum(t *testing.T) {
res := <- Sum(0, 1)
need := 1
if res != need {
t.Errorf("res should be %+v", need)
}
res = <- Sum(1, 2)
need = 3
if res != need {
t.Errorf("res should be %+v", need)
}
}
func TestSumAll(t *testing.T) {
res := SumAll(1)
need := 1
if res != need {
t.Errorf("res should be %+v, got %+v", need, res)
}
res = SumAll(2)
need = 3
if res != need {
t.Errorf("res should be %+v, got %+v", need, res)
}
res = SumAll(3)
need = 6
if res != need {
t.Errorf("res should be %+v, got %+v", need, res)
}
res = SumAll(10)
need = 55
if res != need {
t.Errorf("res should be %+v, got %+v", need, res)
}
res = SumAll(100)
need = 5050
if res != need {
t.Errorf("res should be %+v, got %+v", need, res)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment