|
| 1 | +import env |
| 2 | +import unittest |
| 3 | +from dcclab.analysis import * |
| 4 | + |
| 5 | +def calculateFactorial(inputQueue, outputQueue): |
| 6 | + try: |
| 7 | + value = inputQueue.get_nowait() |
| 8 | + product = 1 |
| 9 | + for i in range(value): |
| 10 | + product *= (i+1) |
| 11 | + outputQueue.put( (value, product) ) |
| 12 | + except Empty as err: |
| 13 | + pass # not an error |
| 14 | + |
| 15 | +def slowCalculation(inputQueue, outputQueue): |
| 16 | + try: |
| 17 | + value = inputQueue.get_nowait() |
| 18 | + time.sleep(3) |
| 19 | + outputQueue.put( value ) |
| 20 | + except Empty as err: |
| 21 | + pass # not an error |
| 22 | + |
| 23 | +def processSimple(queue): |
| 24 | + while not queue.empty(): |
| 25 | + try: |
| 26 | + (n, nfactorial) = queue.get_nowait() |
| 27 | + print('Just finished calculating {0}!'.format(n)) |
| 28 | + except Empty as err: |
| 29 | + break # we are done |
| 30 | + |
| 31 | + |
| 32 | +class MyTestCase(env.DCCLabTestCase): |
| 33 | + def testThreads1(self): |
| 34 | + N = 11 |
| 35 | + print("Calculating n! for numbers 0 to {0} (every calculation is independent)".format(N - 1)) |
| 36 | + print("======================================================================") |
| 37 | + |
| 38 | + print("Using threads: fast startup time appropriate for quick calculations") |
| 39 | + engine = ComputeEngine(useThreads=True) |
| 40 | + for i in range(N): |
| 41 | + engine.inputQueue.put(i) |
| 42 | + engine.compute(target=calculateFactorial) |
| 43 | + |
| 44 | + def testProcesses1(self): |
| 45 | + N = 11 |
| 46 | + print("Using processes: long startup time appropriate for longer calculations") |
| 47 | + engine = ComputeEngine(useThreads=False) |
| 48 | + for i in range(N): |
| 49 | + engine.inputQueue.put(i) |
| 50 | + engine.compute(target=calculateFactorial) |
| 51 | + |
| 52 | + def testThreadsProcessTask(self): |
| 53 | + N = 11 |
| 54 | + print("Using threads and replacing the processTaskResult function") |
| 55 | + engine = ComputeEngine(useThreads=True) |
| 56 | + for i in range(N): |
| 57 | + engine.inputQueue.put(i) |
| 58 | + engine.compute(target=calculateFactorial, processTaskResults=processSimple) |
| 59 | + @unittest.skip |
| 60 | + def testProcessesVeryLong(self): |
| 61 | + N = 11 |
| 62 | + print("Using processes with very long calculations and timeout") |
| 63 | + engine = ComputeEngine(useThreads=False) |
| 64 | + for i in range(N): |
| 65 | + engine.inputQueue.put(i) |
| 66 | + engine.compute(target=slowCalculation, timeoutInSeconds=2) |
| 67 | + |
| 68 | + |
| 69 | +if __name__ == '__main__': |
| 70 | + unittest.main() |
0 commit comments