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