Skip to content

Commit 85a37c1

Browse files
committed
correct demo.py logic
1 parent a8340d7 commit 85a37c1

File tree

2 files changed

+25
-27
lines changed

2 files changed

+25
-27
lines changed

.github/workflows/ci.yml

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,12 @@ jobs:
1818

1919
- run: pip install .[tests,lint]
2020
- run: flake8
21-
- run: mypy .
21+
- run: mypy . src
22+
23+
- run: |
24+
sudo apt update -yq
25+
sudo apt install -yq --no-install-recommends ffmpeg
2226
23-
- run: sudo apt install -yq --no-install-recommends ffmpeg
2427
- run: pytest
2528

2629

demo.py

Lines changed: 20 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,11 @@
44
55
timing on old Windows laptop:
66
7-
python demo.py c
7+
python demo.py c => 2.3 sec.
88
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.
1810
11+
python demo.py p => 0.9 sec.
1912
2013
We didn't break out worker setup time from computation time.
2114
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):
8174
P = ArgumentParser(
8275
description="Demonstrate differences between coroutines, threads and proceses."
8376
)
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")
8578
P.add_argument("-Nworker", help="number of workers", type=int, default=4)
8679
P.add_argument(
8780
"-Niter", help="number of loop iterations (arbitrary)", type=int, default=5000000,
8881
)
8982
A = P.parse_args()
9083

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 = []
9486
tic = time.monotonic()
9587
for i in range(A.Nworker):
9688
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)
9992
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)
10295
)
10396
p.start()
104-
print(
105-
"started process workert {}, PID: {}".format(i, p.pid) # type: ignore
106-
) # type: ignore
97+
ps.append(p)
10798

10899
if A.method == "c":
109100
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

Comments
 (0)