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