Mark non-primes in parallel goroutines

This commit is contained in:
Peter J. Holzer 2021-07-13 00:13:44 +02:00 committed by Peter J. Holzer
parent af97ce448c
commit 12cf4f79ff
1 changed files with 21 additions and 2 deletions

View File

@ -3,15 +3,27 @@ package main
import ( import (
"fmt" "fmt"
"os" "os"
"runtime"
"strconv" "strconv"
"sync"
"time" "time"
) )
var markGroup sync.WaitGroup
func markMultiples(sieve []uint64, i int64, n0, n1 int64) {
for j := n0; j < n1; j += 2 * i {
sieve[j>>7] |= 1 << ((j & 0x7F) >> 1)
}
markGroup.Done()
}
func main() { func main() {
n, err := strconv.ParseInt(os.Args[1], 10, 64) n, err := strconv.ParseInt(os.Args[1], 10, 64)
if err != nil { if err != nil {
panic(err) panic(err)
} }
nCpus := int64(runtime.NumCPU())
t0 := time.Now() t0 := time.Now()
sieve := make([]uint64, (n>>7)+1) sieve := make([]uint64, (n>>7)+1)
var found int64 var found int64
@ -21,9 +33,16 @@ func main() {
for i = 3; i < n; i += 2 { for i = 3; i < n; i += 2 {
if (sieve[i>>7] & (1 << ((i & 0x7F) >> 1))) == 0 { if (sieve[i>>7] & (1 << ((i & 0x7F) >> 1))) == 0 {
found++ found++
for j := i * i; j < n; j += 2 * i {
sieve[j>>7] |= 1 << ((j & 0x7F) >> 1) p := nCpus
var jnext int64
for j := i * i; j < n; j = jnext {
jnext = ((n-j)/(2*i)/p+1)*(2*i) + j
markGroup.Add(1)
go markMultiples(sieve, i, j, jnext)
p--
} }
markGroup.Wait()
} }
} }
d := time.Since(t0) d := time.Since(t0)