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