|
4 | 4 |
|
5 | 5 | timing on old Windows laptop: |
6 | 6 |
|
7 | | - python demo.py c |
| 7 | +python demo.py c => 2.3 sec. |
8 | 8 |
|
9 | | - 8.6 sec. |
10 | | -
|
11 | | - python demo.py t |
12 | | -
|
13 | | - 9.2 sec. |
14 | | -
|
15 | | - python demo.py p |
16 | | -
|
17 | | - 4.5 sec. # multiple CPU cores used simultaneously |
| 9 | +python demo.py t => 2.5 sec. |
18 | 10 |
|
| 11 | +python demo.py p => 0.9 sec. |
19 | 12 |
|
20 | 13 | We didn't break out worker setup time from computation time. |
21 | 14 | In real-world situations, coroutines can be faster and less resource-consuming than threads. |
@@ -81,33 +74,35 @@ def mp_worker(i: int, Niter: int, tic: float): |
81 | 74 | P = ArgumentParser( |
82 | 75 | description="Demonstrate differences between coroutines, threads and proceses." |
83 | 76 | ) |
84 | | - P.add_argument("method", help="c: coroutine, t: threading, p: multiprocessing") |
| 77 | + P.add_argument("method", choices=["c", "t", "p"], help="c: coroutine, t: threading, p: multiprocessing") |
85 | 78 | P.add_argument("-Nworker", help="number of workers", type=int, default=4) |
86 | 79 | P.add_argument( |
87 | 80 | "-Niter", help="number of loop iterations (arbitrary)", type=int, default=5000000, |
88 | 81 | ) |
89 | 82 | A = P.parse_args() |
90 | 83 |
|
91 | | - if A.method not in ("c", "t", "p"): |
92 | | - raise ValueError("Method must be one of: c t p") |
93 | | - |
| 84 | + ps = [] |
| 85 | + ts = [] |
94 | 86 | tic = time.monotonic() |
95 | 87 | for i in range(A.Nworker): |
96 | 88 | if A.method == "t": |
97 | | - p = Thread_worker(i, A.Niter) # type: ignore |
98 | | - p.start() |
| 89 | + t = Thread_worker(i, A.Niter) |
| 90 | + t.start() |
| 91 | + ts.append(t) |
99 | 92 | elif A.method == "p": |
100 | | - p = multiprocessing.Process( # type: ignore |
101 | | - target=mp_worker, args=(i, A.Niter, tic) # type: ignore |
| 93 | + p = multiprocessing.Process( |
| 94 | + target=mp_worker, args=(i, A.Niter, tic) |
102 | 95 | ) |
103 | 96 | p.start() |
104 | | - print( |
105 | | - "started process workert {}, PID: {}".format(i, p.pid) # type: ignore |
106 | | - ) # type: ignore |
| 97 | + ps.append(p) |
107 | 98 |
|
108 | 99 | if A.method == "c": |
109 | 100 | runner(coro, A.Nworker, A.Niter, tic) |
110 | | - else: |
111 | | - p.join() |
112 | | - |
113 | | - print("{:.2f} sec.".format(time.monotonic() - tic)) |
| 101 | + elif A.method == "p": |
| 102 | + for p in ps: |
| 103 | + p.join() |
| 104 | + elif A.method == "t": |
| 105 | + for t in ts: |
| 106 | + t.join() |
| 107 | + |
| 108 | + print(f"Elapsed wallclock time: {time.monotonic() - tic:.2f} sec.") |
0 commit comments