1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/examples/simple_managed_queue.py Sat Sep 15 15:57:34 2007 +0000
1.3 @@ -0,0 +1,66 @@
1.4 +#!/usr/bin/env python
1.5 +
1.6 +"""
1.7 +A simple example of parallel computation using a queue and managed callables.
1.8 +"""
1.9 +
1.10 +import pprocess
1.11 +import time
1.12 +
1.13 +# Array size and a limit on the number of processes.
1.14 +
1.15 +N = 10
1.16 +limit = 10
1.17 +delay = 1
1.18 +
1.19 +# Work function and monitoring class.
1.20 +
1.21 +def calculate(i, j):
1.22 +
1.23 + """
1.24 + A supposedly time-consuming calculation on 'i' and 'j'.
1.25 + """
1.26 +
1.27 + time.sleep(delay)
1.28 + return (i, j, i * N + j)
1.29 +
1.30 +# Main program.
1.31 +
1.32 +if __name__ == "__main__":
1.33 +
1.34 + # Initialise the communications queue with a limit on the number of
1.35 + # channels/processes.
1.36 +
1.37 + queue = pprocess.Queue(limit=limit)
1.38 + t = time.time()
1.39 +
1.40 + # Initialise an array.
1.41 +
1.42 + results = [0] * N * N
1.43 +
1.44 + # Wrap the calculate function and manage it.
1.45 +
1.46 + calc = queue.manage(pprocess.MakeParallel(calculate))
1.47 +
1.48 + # Perform the work.
1.49 +
1.50 + print "Calculating..."
1.51 + for i in range(0, N):
1.52 + for j in range(0, N):
1.53 + calc(i, j)
1.54 +
1.55 + # Store the results as they arrive.
1.56 +
1.57 + print "Finishing..."
1.58 + for i, j, result in queue:
1.59 + results[i*N+j] = result
1.60 +
1.61 + # Show the results.
1.62 +
1.63 + print "Time taken:", time.time() - t
1.64 + for i in range(0, N):
1.65 + for result in results[i*N:i*N+N]:
1.66 + print result,
1.67 + print
1.68 +
1.69 +# vim: tabstop=4 expandtab shiftwidth=4