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