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