From e2e4685fed86a6a5fad4a96ec8d4bd6055c6a7dc Mon Sep 17 00:00:00 2001 From: datalore Date: Mon, 30 Sep 2024 19:43:46 +0200 Subject: [PATCH] feat(generatePrimes): Added option to override number of routines --- README.md | 1 + main.go | 20 ++++++++++++-------- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index a10fcaf..117f685 100644 --- a/README.md +++ b/README.md @@ -16,3 +16,4 @@ Flags: - `-p`: Calculate and save prime list up to the given number. If not given, the given number will be split into primes. If not all necessary prime numbers are in the list, the necessary primes will be calculated before, but they will not be saved. - `-d`: Don't load `prime.txt`. This results in calculation starting from zero. +- `-r n`: Use *n* routines to calculate. 0 = number of available CPU cores. This is the default. diff --git a/main.go b/main.go index 73eccf9..cac7e11 100644 --- a/main.go +++ b/main.go @@ -50,7 +50,7 @@ func checkIsDivisibleByPrime(number, offset, stride int, primes *[]int, resultCh resultChannel <- false } -func generatePrimes(upperLimit int, loadList bool) []int { +func generatePrimes(upperLimit int, loadList bool, numRoutines int) []int { var primes []int bootTime := time.Now() @@ -61,7 +61,9 @@ func generatePrimes(upperLimit int, loadList bool) []int { primes = []int{2, 3, 5} } - numRoutines := runtime.NumCPU() + if numRoutines == 0 { + numRoutines = runtime.NumCPU() + } fmt.Printf("Startup time: %v\nCalculating with %d routines\n\n", time.Now().Sub(bootTime), numRoutines) @@ -143,9 +145,11 @@ func calculatePrimeParts(number int, primes []int) []int { func main() { var primeList bool var dontLoad bool + var numRoutines int flag.BoolVar(&primeList, "p", false, "Only calculate and print prime list") flag.BoolVar(&dontLoad, "d", false, "Don't load precalculated primes, calculate from 0") + flag.IntVar(&numRoutines, "r", 0, "How many routines to use for calculation. 0 = number of available CPU cores") flag.Parse() numStr := flag.Arg(0) @@ -161,14 +165,14 @@ func main() { } if primeList { - onlyGenerate(number, dontLoad) + onlyGenerate(number, dontLoad, numRoutines) } else { - calculate(number, dontLoad) + calculate(number, dontLoad, numRoutines) } } -func onlyGenerate(number int, dontLoad bool) { - primes := generatePrimes(number, !dontLoad) +func onlyGenerate(number int, dontLoad bool, numRoutines int) { + primes := generatePrimes(number, !dontLoad, numRoutines) file, err := os.Create("prime.txt") if err != nil { @@ -185,8 +189,8 @@ func onlyGenerate(number int, dontLoad bool) { file.Close() } -func calculate(number int, dontLoad bool) { - primes := generatePrimes(number, !dontLoad) +func calculate(number int, dontLoad bool, numRoutines int) { + primes := generatePrimes(number, !dontLoad, numRoutines) primeParts := calculatePrimeParts(number, primes)