|
| 1 | +""" |
| 2 | +WIP |
| 3 | +
|
| 4 | +Based on: |
| 5 | +http://chriskiehl.com/article/parallelism-in-one-line/ |
| 6 | +""" |
| 7 | +import timeit |
| 8 | +import urllib2 |
| 9 | + |
| 10 | +# starts a new process for each worker, |
| 11 | +# parallel |
| 12 | +from multiprocessing import Pool as ProcessPool |
| 13 | + |
| 14 | +# multiple threads but all subject to the GIL, |
| 15 | +# concurrent but not parallel |
| 16 | +from multiprocessing.dummy import Pool as ThreadPool |
| 17 | + |
| 18 | + |
| 19 | +urls = [ |
| 20 | + 'http://www.python.org', |
| 21 | + 'http://www.google.com', |
| 22 | + 'http://stackoverflow.com', |
| 23 | +] |
| 24 | + |
| 25 | + |
| 26 | +def serial_network_bound_work(): |
| 27 | + results = map(urllib2.urlopen, urls) |
| 28 | + return results |
| 29 | + |
| 30 | + |
| 31 | +def processed_network_bound_work(): |
| 32 | + # Make the Pool of workers |
| 33 | + pool = ProcessPool(4) |
| 34 | + # Open the urls in their own threads |
| 35 | + # and return the results |
| 36 | + results = pool.map(urllib2.urlopen, urls) |
| 37 | + # close the pool and wait for the work to finish |
| 38 | + pool.close() |
| 39 | + pool.join() |
| 40 | + return results |
| 41 | + |
| 42 | + |
| 43 | +def threaded_network_bound_work(): |
| 44 | + # Make the Pool of workers |
| 45 | + pool = ThreadPool(4) |
| 46 | + # Open the urls in their own threads |
| 47 | + # and return the results |
| 48 | + results = pool.map(urllib2.urlopen, urls) |
| 49 | + # close the pool and wait for the work to finish |
| 50 | + pool.close() |
| 51 | + pool.join() |
| 52 | + return results |
| 53 | + |
| 54 | + |
| 55 | +def processed_cpu_bound_work(): |
| 56 | + pass |
| 57 | + |
| 58 | + |
| 59 | +def threaded_cpu_bound_work(): |
| 60 | + pass |
| 61 | + |
| 62 | + |
| 63 | +if __name__ == '__main__': |
| 64 | + def benchmark(func): |
| 65 | + func_name = func.name |
| 66 | + print(timeit.timeit( |
| 67 | + '{func_name}()'.format(func_name=func_name), |
| 68 | + setup='from __main__ import {func_name}'.format(func_name=func_name) |
| 69 | + )) |
| 70 | + |
| 71 | + map(benchmark, [ |
| 72 | + serial_network_bound_work, |
| 73 | + processed_network_bound_work, |
| 74 | + threaded_network_bound_work, |
| 75 | + processed_cpu_bound_work, |
| 76 | + threaded_cpu_bound_work, |
| 77 | + ]) |
0 commit comments