forked from Consensys/gnark-crypto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
execute.go
44 lines (36 loc) · 840 Bytes
/
execute.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
package parallel
import (
"runtime"
"sync"
)
// Execute process in parallel the work function
func Execute(nbIterations int, work func(int, int), maxCpus ...int) {
nbTasks := runtime.NumCPU()
if len(maxCpus) == 1 {
nbTasks = maxCpus[0]
}
nbIterationsPerCpus := nbIterations / nbTasks
// more CPUs than tasks: a CPU will work on exactly one iteration
if nbIterationsPerCpus < 1 {
nbIterationsPerCpus = 1
nbTasks = nbIterations
}
var wg sync.WaitGroup
extraTasks := nbIterations - (nbTasks * nbIterationsPerCpus)
extraTasksOffset := 0
for i := 0; i < nbTasks; i++ {
wg.Add(1)
_start := i*nbIterationsPerCpus + extraTasksOffset
_end := _start + nbIterationsPerCpus
if extraTasks > 0 {
_end++
extraTasks--
extraTasksOffset++
}
go func() {
work(_start, _end)
wg.Done()
}()
}
wg.Wait()
}