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 the start method. |
paulb@106 | 5 | """ |
paulb@106 | 6 | |
paulb@106 | 7 | import pprocess |
paulb@106 | 8 | import time |
paulb@112 | 9 | #import random |
paulb@106 | 10 | |
paulb@106 | 11 | # Array size and a limit on the number of processes. |
paulb@106 | 12 | |
paulb@106 | 13 | N = 10 |
paulb@106 | 14 | limit = 10 |
paulb@106 | 15 | delay = 1 |
paulb@106 | 16 | |
paulb@106 | 17 | # Work function. |
paulb@106 | 18 | |
paulb@106 | 19 | def calculate(i, j): |
paulb@106 | 20 | |
paulb@106 | 21 | "A supposedly time-consuming calculation on 'i' and 'j'." |
paulb@106 | 22 | |
paulb@112 | 23 | #time.sleep(delay * random.random()) |
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@109 | 31 | t = time.time() |
paulb@109 | 32 | |
paulb@106 | 33 | # Initialise the communications queue with a limit on the number of |
paulb@106 | 34 | # channels/processes. |
paulb@106 | 35 | |
paulb@106 | 36 | queue = pprocess.Queue(limit=limit) |
paulb@106 | 37 | |
paulb@106 | 38 | # Initialise an array. |
paulb@106 | 39 | |
paulb@106 | 40 | results = [0] * N * N |
paulb@106 | 41 | |
paulb@106 | 42 | # Wrap the calculate function. |
paulb@106 | 43 | |
paulb@106 | 44 | calc = pprocess.MakeParallel(calculate) |
paulb@106 | 45 | |
paulb@106 | 46 | # Perform the work. |
paulb@106 | 47 | |
paulb@106 | 48 | for i in range(0, N): |
paulb@106 | 49 | for j in range(0, N): |
paulb@106 | 50 | queue.start(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 | for i in range(0, N): |
paulb@106 | 61 | for result in results[i*N:i*N+N]: |
paulb@106 | 62 | print result, |
paulb@106 | 63 | print |
paulb@106 | 64 | |
paulb@109 | 65 | print "Time taken:", time.time() - t |
paulb@109 | 66 | |
paulb@106 | 67 | # vim: tabstop=4 expandtab shiftwidth=4 |