feat(generatePrimes): number of routines now dependent on number of CPUs

This commit is contained in:
datalore 2024-09-30 18:28:51 +02:00
parent d3481d22af
commit 28c5f51aa9

View File

@ -7,6 +7,7 @@ import (
"fmt" "fmt"
"log" "log"
"os" "os"
"runtime"
"strconv" "strconv"
"time" "time"
) )
@ -52,12 +53,18 @@ func checkIsDivisibleByPrime(number, offset, stride int, primes *[]int, resultCh
func generatePrimes(upperLimit int, loadList bool) []int { func generatePrimes(upperLimit int, loadList bool) []int {
var primes []int var primes []int
bootTime := time.Now()
if loadList { if loadList {
primes = loadPrimes() primes = loadPrimes()
} else { } else {
primes = []int{2, 3, 5} primes = []int{2, 3, 5}
} }
numRoutines := runtime.NumCPU()
fmt.Printf("Startup time: %v\nCalculating with %d routines\n\n", time.Now().Sub(bootTime), numRoutines)
progress := make(chan float32) progress := make(chan float32)
go printProgress(progress, "Generating primes") go printProgress(progress, "Generating primes")
@ -73,7 +80,6 @@ func generatePrimes(upperLimit int, loadList bool) []int {
checkCtx, checkCancel := context.WithCancel(context.Background()) checkCtx, checkCancel := context.WithCancel(context.Background())
resultChannel := make(chan bool) resultChannel := make(chan bool)
numRoutines := 12
for r := 0; r < numRoutines; r++ { for r := 0; r < numRoutines; r++ {
go checkIsDivisibleByPrime(i, r, numRoutines, &primes, resultChannel, checkCtx) go checkIsDivisibleByPrime(i, r, numRoutines, &primes, resultChannel, checkCtx)