-
Notifications
You must be signed in to change notification settings - Fork 0
/
multiadd.go
79 lines (72 loc) · 1.31 KB
/
multiadd.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package main
import (
"flag"
"fmt"
"log"
"os"
"runtime"
"runtime/pprof"
"sync"
)
var LIMIT uint64 = 20000000000
var ngoroutines = flag.Int("goroutines", 0, "number of goroutines to use")
func main() {
cpuprofile := flag.String("cpuprofile", "", "write cpu profile to file")
flag.Parse()
if *cpuprofile != "" {
f, err := os.Create(*cpuprofile)
if err != nil {
log.Fatal(err)
}
pprof.StartCPUProfile(f)
defer func() {
pprof.StopCPUProfile()
fmt.Println("stopped cpu profile")
}()
}
if flag.Arg(0) == "1" || flag.Arg(0) == "" {
main1()
} else if flag.Arg(0) == "2" {
main2()
} else {
fmt.Println("\033[31;mBad input\033[m")
os.Exit(1)
}
}
func main1() {
var total uint64
var i uint64
for i = 0; i < LIMIT; i++ {
total += i
}
fmt.Println(total)
}
func main2() {
var n uint64
if *ngoroutines == 0 {
n = uint64(runtime.GOMAXPROCS(0))
} else {
n = uint64(*ngoroutines)
}
fmt.Println("GOMAXPROCS", n)
sums := make([]uint64, n)
wg := sync.WaitGroup{}
var i uint64
for i = 0; i < n; i++ {
wg.Add(1)
go func(i uint64) {
var start uint64 = (LIMIT / n) * i
var end = start + (LIMIT / n)
for j := start; j < end; j += 1 {
sums[i] += j
}
wg.Done()
}(uint64(i))
}
wg.Wait()
var total uint64
for _, s := range sums {
total += s
}
fmt.Println(total)
}