Skip to content
{{ message }}

Instantly share code, notes, and snippets.

# mikeckennedy/primes-parallel.py

Created Mar 21, 2021
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/
 # 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()
to join this conversation on GitHub. Already have an account? Sign in to comment