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