2007-09-16 | paulb | file changeset files shortlog | [project @ 2007-09-16 19:38:51 by paulb] Changed the source package name. |
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, appending results |
paulb@109 | 5 | to a list/array. |
paulb@109 | 6 | """ |
paulb@109 | 7 | |
paulb@109 | 8 | import time |
paulb@112 | 9 | #import random |
paulb@109 | 10 | |
paulb@109 | 11 | # Array size. |
paulb@109 | 12 | |
paulb@109 | 13 | N = 10 |
paulb@109 | 14 | delay = 1 |
paulb@109 | 15 | |
paulb@109 | 16 | # Work function. |
paulb@109 | 17 | |
paulb@109 | 18 | def calculate(i, j): |
paulb@109 | 19 | |
paulb@109 | 20 | """ |
paulb@109 | 21 | A supposedly time-consuming calculation on 'i' and 'j'. |
paulb@109 | 22 | """ |
paulb@109 | 23 | |
paulb@112 | 24 | #time.sleep(delay * random.random()) |
paulb@109 | 25 | time.sleep(delay) |
paulb@109 | 26 | return i * N + j |
paulb@109 | 27 | |
paulb@109 | 28 | # Main program. |
paulb@109 | 29 | |
paulb@109 | 30 | if __name__ == "__main__": |
paulb@109 | 31 | |
paulb@109 | 32 | t = time.time() |
paulb@109 | 33 | |
paulb@109 | 34 | # Initialise an array. |
paulb@109 | 35 | |
paulb@109 | 36 | results = [] |
paulb@109 | 37 | |
paulb@109 | 38 | # Perform the work. |
paulb@109 | 39 | |
paulb@109 | 40 | print "Calculating..." |
paulb@109 | 41 | for i in range(0, N): |
paulb@109 | 42 | for j in range(0, N): |
paulb@109 | 43 | results.append(calculate(i, j)) |
paulb@109 | 44 | |
paulb@109 | 45 | # Show the results. |
paulb@109 | 46 | |
paulb@109 | 47 | for i in range(0, N): |
paulb@109 | 48 | for result in results[i*N:i*N+N]: |
paulb@109 | 49 | print result, |
paulb@109 | 50 | print |
paulb@109 | 51 | |
paulb@109 | 52 | print "Time taken:", time.time() - t |
paulb@109 | 53 | |
paulb@109 | 54 | # vim: tabstop=4 expandtab shiftwidth=4 |