2007-09-15 | paulb | file changeset files shortlog | [project @ 2007-09-15 19:42:24 by paulb] Tidied up the examples. Added more sequential example programs and a program demonstrating usage of the Map class directly. |
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@96 | 9 | |
paulb@96 | 10 | # Array size and a limit on the number of processes. |
paulb@96 | 11 | |
paulb@96 | 12 | N = 10 |
paulb@98 | 13 | limit = 10 |
paulb@96 | 14 | delay = 1 |
paulb@96 | 15 | |
paulb@96 | 16 | # Work function. |
paulb@96 | 17 | |
paulb@96 | 18 | def calculate(t): |
paulb@96 | 19 | |
paulb@96 | 20 | "A supposedly time-consuming calculation on 't'." |
paulb@96 | 21 | |
paulb@96 | 22 | i, j = t |
paulb@96 | 23 | time.sleep(delay) |
paulb@96 | 24 | return i * N + j |
paulb@96 | 25 | |
paulb@96 | 26 | # Main program. |
paulb@96 | 27 | |
paulb@96 | 28 | if __name__ == "__main__": |
paulb@96 | 29 | |
paulb@96 | 30 | t = time.time() |
paulb@96 | 31 | |
paulb@106 | 32 | # Initialise an array. |
paulb@106 | 33 | |
paulb@96 | 34 | sequence = [] |
paulb@96 | 35 | for i in range(0, N): |
paulb@96 | 36 | for j in range(0, N): |
paulb@96 | 37 | sequence.append((i, j)) |
paulb@96 | 38 | |
paulb@106 | 39 | # Perform the work. |
paulb@106 | 40 | |
paulb@96 | 41 | results = pprocess.pmap(calculate, sequence, limit=limit) |
paulb@96 | 42 | |
paulb@106 | 43 | # Show the results. |
paulb@106 | 44 | |
paulb@96 | 45 | for i in range(0, N): |
paulb@96 | 46 | for result in results[i*N:i*N+N]: |
paulb@96 | 47 | print result, |
paulb@96 | 48 | print |
paulb@96 | 49 | |
paulb@109 | 50 | print "Time taken:", time.time() - t |
paulb@109 | 51 | |
paulb@96 | 52 | # vim: tabstop=4 expandtab shiftwidth=4 |