paulb@96 | 1 | #!/usr/bin/env python |
paulb@96 | 2 | |
paulb@96 | 3 | """ |
paulb@96 | 4 | A simple example of parallel computation using exchanges and managed callables. |
paulb@96 | 5 | """ |
paulb@96 | 6 | |
paulb@96 | 7 | import pprocess |
paulb@96 | 8 | import time |
paulb@96 | 9 | |
paulb@96 | 10 | # Array size and a limit on the number of processes. |
paulb@96 | 11 | |
paulb@96 | 12 | N = 10 |
paulb@96 | 13 | limit = 10 |
paulb@96 | 14 | delay = 1 |
paulb@96 | 15 | |
paulb@96 | 16 | # Work function and monitoring class. |
paulb@96 | 17 | |
paulb@106 | 18 | def calculate(i, j): |
paulb@96 | 19 | |
paulb@96 | 20 | """ |
paulb@106 | 21 | A supposedly time-consuming calculation on 'i' and 'j'. |
paulb@96 | 22 | """ |
paulb@96 | 23 | |
paulb@96 | 24 | time.sleep(delay) |
paulb@106 | 25 | return (i, j, i * N + j) |
paulb@96 | 26 | |
paulb@96 | 27 | class MyExchange(pprocess.Exchange): |
paulb@96 | 28 | |
paulb@96 | 29 | "Parallel convenience class containing the array assignment operation." |
paulb@96 | 30 | |
paulb@96 | 31 | def store_data(self, ch): |
paulb@96 | 32 | i, j, result = ch.receive() |
paulb@96 | 33 | self.D[i*N+j] = result |
paulb@96 | 34 | |
paulb@96 | 35 | # Main program. |
paulb@96 | 36 | |
paulb@96 | 37 | if __name__ == "__main__": |
paulb@96 | 38 | |
paulb@96 | 39 | # Initialise the communications exchange with a limit on the number of |
paulb@96 | 40 | # channels/processes. |
paulb@96 | 41 | |
paulb@96 | 42 | exchange = MyExchange(limit=limit) |
paulb@96 | 43 | t = time.time() |
paulb@96 | 44 | |
paulb@96 | 45 | # Initialise an array - it is stored in the exchange to permit automatic |
paulb@96 | 46 | # assignment of values as the data arrives. |
paulb@96 | 47 | |
paulb@96 | 48 | exchange.D = [0] * N * N |
paulb@106 | 49 | |
paulb@106 | 50 | # Wrap the calculate function and manage it. |
paulb@106 | 51 | |
paulb@106 | 52 | calc = exchange.manage(pprocess.MakeParallel(calculate)) |
paulb@106 | 53 | |
paulb@106 | 54 | # Perform the work. |
paulb@96 | 55 | |
paulb@96 | 56 | print "Calculating..." |
paulb@96 | 57 | for i in range(0, N): |
paulb@96 | 58 | for j in range(0, N): |
paulb@96 | 59 | calc(i, j) |
paulb@96 | 60 | |
paulb@106 | 61 | # Wait for the results. |
paulb@106 | 62 | |
paulb@96 | 63 | print "Finishing..." |
paulb@96 | 64 | exchange.finish() |
paulb@96 | 65 | |
paulb@106 | 66 | # Show the results. |
paulb@106 | 67 | |
paulb@96 | 68 | print "Time taken:", time.time() - t |
paulb@96 | 69 | for i in range(0, N): |
paulb@96 | 70 | for result in exchange.D[i*N:i*N+N]: |
paulb@96 | 71 | print result, |
paulb@96 | 72 | print |
paulb@96 | 73 | |
paulb@96 | 74 | # vim: tabstop=4 expandtab shiftwidth=4 |