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