Update tests / test harness.
[python_utils.git] / tests / parallelize_itest.py
1 #!/usr/bin/env python3
2
3 import random
4 import sys
5
6 import bootstrap
7 import parallelize as p
8 import decorator_utils
9 import executors
10 import math_utils
11 import smart_future
12
13
14 @p.parallelize(method=p.Method.THREAD)
15 def compute_factorial_thread(n):
16     total = 1
17     for x in range(2, n):
18         total *= x
19     return total
20
21
22 @p.parallelize(method=p.Method.PROCESS)
23 def compute_factorial_process(n):
24     total = 1
25     for x in range(2, n):
26         total *= x
27     return total
28
29
30 @p.parallelize(method=p.Method.REMOTE)
31 def list_primes(n):
32     """Calculates sum of all primes below given integer n"""
33     ret = []
34     for x in range(2, n):
35         ret.append(math_utils.is_prime(x))
36     return ret
37
38
39 @decorator_utils.timed
40 def test_thread_parallelization() -> None:
41     results = []
42     for _ in range(50):
43         results.append(compute_factorial_thread(_))
44     smart_future.wait_all(results)
45     for future in results:
46         print(f'Thread: {future}')
47     texecutor = executors.DefaultExecutors().thread_pool()
48     texecutor.shutdown()
49
50
51 @decorator_utils.timed
52 def test_process_parallelization() -> None:
53     results = []
54     for _ in range(50):
55         results.append(compute_factorial_process(_))
56     for future in smart_future.wait_any(results):
57         print(f'Process: {future}')
58     pexecutor = executors.DefaultExecutors().process_pool()
59     pexecutor.shutdown()
60
61
62 @decorator_utils.timed
63 def test_remote_parallelization() -> None:
64     results = {}
65     for _ in range(50):
66         n = random.randint(0, 100000)
67         results[n] = list_primes(n)
68     tot = 0
69     for _ in results[n]:
70         tot += _
71     print(tot)
72     rexecutor = executors.DefaultExecutors().remote_pool()
73     rexecutor.shutdown()
74
75
76 @bootstrap.initialize
77 def main() -> None:
78     test_thread_parallelization()
79     test_process_parallelization()
80     test_remote_parallelization()
81     sys.exit(0)
82
83
84 if __name__ == '__main__':
85     main()