import threading import multiprocessing import concurrent.futures import time
test = [7, 7, 7, 7, 7]
defjob(x): ''' x = x * x time.sleep(5) # Use `time.sleep()` to test effectiveness for paralleling is a wrong example. return x ''' s = 0 for i inrange(10**x): s = s + 1 return s
defrunBaseLine(): """Baseline""" starttime = time.time() for i in test: job(i) print('Baseline: {:0.3f} seconds'.format(time.time() - starttime))
defrunMultithread(): """Use threading""" threads = list() starttime = time.time() for element in test: threads.append(threading.Thread(target=job, args=(element,))) for thread in threads: thread.start() for thread in threads: thread.join() print('Multithread: {:0.3f} seconds'.format(time.time() - starttime))
defrunMultiprocessing(): """Use multiprocessing""" starttime = time.time() processes = [] for i in test: p = multiprocessing.Process(target=job, args=(i,)) processes.append(p) p.start() for process in processes: process.join() print('Multiprocessing: {:0.3f} seconds'.format(time.time() - starttime))
defrunMultiprocessingUsingPool(): """Use multiprocessing with pool""" starttime = time.time() with multiprocessing.Pool() as p: p.map(job, test) print('Multiprocessing pool: {:0.3f} seconds'.format(time.time() - starttime))
defrunMultiprocessingUsingExePool(max_workers=8): """Use high-level multiprocessing class""" starttime = time.time() with concurrent.futures.ProcessPoolExecutor(max_workers=max_workers) as executor: results = executor.map(job, test) print('Multiprocessing pool executor: {:0.3f} seconds'.format(time.time() - starttime))
defrunMultithreadingUsingExePool(max_workers=8): """Use high-level multithreading class""" starttime = time.time() with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor: results = executor.map(job, test) print('Multithreading pool executor: {:0.3f} seconds'.format(time.time() - starttime))