Created
March 21, 2021 19:46
-
-
Save mikeckennedy/ffe8a65473e974d0582da0c74a8f1c67 to your computer and use it in GitHub Desktop.
Proper parallel version of Raspberry Pi cluster code from https://www.the-diy-life.com/can-my-water-cooled-raspberry-pi-cluster-beat-my-macbook/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Requires pip install unsync | |
import time | |
from unsync import unsync | |
import multiprocessing as mp | |
import sys | |
#Start and end numbers | |
start_number = 1 | |
num_processes = mp.cpu_count() | |
def chunks(seq, chunks): | |
size = len(seq) | |
start = 0 | |
for i in range(1, chunks + 1): | |
stop = i * size // chunks | |
yield seq[start:stop] | |
start = stop | |
@unsync(cpu_bound=True) | |
def find_in_range(seq): | |
noPrimes = 0 | |
#Loop through each number, then through the factors to identify prime numbers | |
primes = [] | |
for candidate_number in seq: | |
found_prime = True | |
for div_number in range(2, candidate_number): | |
if candidate_number % div_number == 0: | |
found_prime = False | |
break | |
if found_prime: | |
primes.append(candidate_number) | |
noPrimes += 1 | |
return primes | |
def run(): | |
#Create variable to store the pr | |
# ime numbers and a counter | |
primes = [] | |
ranges = chunks(list(range(2, upper_bound)), num_processes) | |
# for l in ranges: | |
# print(list(l)) | |
# print(len(list(ranges))) | |
#Record the test start time | |
start = time.time() | |
tasks = [] | |
for r in ranges: | |
tasks.append(find_in_range(r)) | |
for t in tasks: | |
# print(t.result()) | |
primes.extend(t.result()) | |
#Once all numbers have been searched, stop the timer | |
end = round(time.time() - start, 2) | |
#Display the results, uncomment the last to list the prime numbers found | |
print('Find all primes up to: ' + str(upper_bound)) | |
print('Time elasped: ' + str(end) + ' seconds') | |
print('Number of primes found ' + str(len(primes))) | |
#print(primes) | |
if __name__ == "__main__": | |
upper_bound = int(input("Number of primes: ")) | |
print(f"Using {num_processes} cores.") | |
run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment