from multiprocessing import Process from random import randint from time import time # This example compare the speed of CPU-bound operations # when using a sequential method and also when using a # multi-process method with the 'multiprocessing' Python # package def calculatePrimeFactors(n): primfac = [] d = 2 while d*d <= n: while (n % d) == 0: primfac.append(d) # supposing you want multiple factors repeated n //= d d += 1 if n > 1: primfac.append(n) return primfac # Sequential Example def seq_crunch(): print("Starting sequential number crunching") t0 = time() for i in range(10000): rand = randint(20000, 100000000) calculatePrimeFactors(rand) t1 = time() return f'{t1-t0:.2f}' # Multi-processing Example def executeProc(): for i in range(1000): rand = randint(20000, 100000000) calculatePrimeFactors(rand) def multi_proc_crunch(): print("Starting multi-process number crunching") t0 = time() processes = [] # Here we create our processes and kick them off for i in range(10): proc = Process(target=executeProc, args=()) processes.append(proc) proc.start() # Again we use the .join() method in order to wait for # execution to finish for all of our processes for process in processes: process.join() t1 = time() return f'{t1-t0:.2f}' if __name__ == '__main__': seq_time = seq_crunch() multi_proc_time = multi_proc_crunch() print('\n==================================') print(f'Time to crunch prime factors sequentially: {seq_time}s') print(f'Time to crunch prime factors using multi-processing: {multi_proc_time}s') print('==================================')