paulb@112 | 1 | #!/usr/bin/env python |
paulb@112 | 2 | |
paulb@112 | 3 | """ |
paulb@112 | 4 | A simple example of parallel computation using a map and the create function. |
paulb@112 | 5 | |
paulb@112 | 6 | NOTE: We could use the with statement in the innermost loop to package the |
paulb@112 | 7 | NOTE: try...finally functionality. |
paulb@112 | 8 | """ |
paulb@112 | 9 | |
paulb@112 | 10 | import pprocess |
paulb@112 | 11 | import time |
paulb@112 | 12 | #import random |
paulb@112 | 13 | |
paulb@112 | 14 | # Array size and a limit on the number of processes. |
paulb@112 | 15 | |
paulb@112 | 16 | N = 10 |
paulb@112 | 17 | limit = 10 |
paulb@112 | 18 | delay = 1 |
paulb@112 | 19 | |
paulb@112 | 20 | # Main program. |
paulb@112 | 21 | |
paulb@112 | 22 | if __name__ == "__main__": |
paulb@112 | 23 | |
paulb@112 | 24 | t = time.time() |
paulb@112 | 25 | |
paulb@112 | 26 | # Initialise the results using a map with a limit on the number of |
paulb@112 | 27 | # channels/processes. |
paulb@112 | 28 | |
paulb@112 | 29 | results = pprocess.Map(limit=limit) |
paulb@112 | 30 | |
paulb@112 | 31 | # Perform the work. |
paulb@112 | 32 | # NOTE: Could use the with statement in the loop to package the |
paulb@112 | 33 | # NOTE: try...finally functionality. |
paulb@112 | 34 | |
paulb@112 | 35 | print "Calculating..." |
paulb@112 | 36 | for i in range(0, N): |
paulb@112 | 37 | for j in range(0, N): |
paulb@112 | 38 | ch = results.create() |
paulb@112 | 39 | if ch: |
paulb@112 | 40 | try: # Calculation work. |
paulb@112 | 41 | |
paulb@112 | 42 | #time.sleep(delay * random.random()) |
paulb@112 | 43 | time.sleep(delay) |
paulb@112 | 44 | ch.send(i * N + j) |
paulb@112 | 45 | |
paulb@112 | 46 | finally: # Important finalisation. |
paulb@112 | 47 | |
paulb@112 | 48 | pprocess.exit(ch) |
paulb@112 | 49 | |
paulb@112 | 50 | # Show the results. |
paulb@112 | 51 | |
paulb@112 | 52 | for i in range(0, N): |
paulb@112 | 53 | for result in results[i*N:i*N+N]: |
paulb@112 | 54 | print result, |
paulb@112 | 55 | print |
paulb@112 | 56 | |
paulb@112 | 57 | print "Time taken:", time.time() - t |
paulb@112 | 58 | |
paulb@112 | 59 | # vim: tabstop=4 expandtab shiftwidth=4 |