Skip to content

Commit cb4436c

Browse files
committed
提交文章 fake thread
1 parent dfc144e commit cb4436c

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

taiyangxue/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# Python 代码实例
22

3+
- [fake-thread](https://github.com/JustDoPython/python-examples/tree/master/taiyangxue/fake-thread) : Python 多线程居然是 —— 假的?
34
- [logging-train](https://github.com/JustDoPython/python-examples/tree/master/taiyangxue/logging-train) : 神器 logging,你真的了解吗?
45
- [split-video](https://github.com/JustDoPython/python-examples/tree/master/taiyangxue/split-video) : 神器 ffmpeg —— 实现短视频批量化操作
56
- [pypandoc](https://github.com/JustDoPython/python-examples/tree/master/taiyangxue/pypandoc) : 神器 Pypandoc —— 实现电子书自由

taiyangxue/fake-thread/main.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import time
2+
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
3+
4+
def gcd(pair):
5+
'''
6+
求解最大公约数
7+
'''
8+
a, b = pair
9+
low = min(a, b)
10+
for i in range(low, 0, -1):
11+
if a % i == 0 and b % i == 0:
12+
return i
13+
14+
assert False, "Not reachable"
15+
16+
# 待求解的数据
17+
NUMBERS = [
18+
(1963309, 2265973), (5948475, 2734765),
19+
(1876435, 4765849), (7654637, 3458496),
20+
(1823712, 1924928), (2387454, 5873948),
21+
(1239876, 2987473), (3487248, 2098437),
22+
(1963309, 2265973), (5948475, 2734765),
23+
(1876435, 4765849), (7654637, 3458496),
24+
(1823712, 1924928), (2387454, 5873948),
25+
(1239876, 2987473), (3487248, 2098437),
26+
(3498747, 4563758), (1298737, 2129874)
27+
]
28+
29+
if __name__ == '__main__':
30+
## 顺序求解
31+
start = time.time()
32+
results = list(map(gcd, NUMBERS))
33+
end = time.time()
34+
delta = end - start
35+
print(f'顺序执行时间: {delta:.3f} 秒')
36+
37+
## 多线程求解
38+
start = time.time()
39+
pool1 = ThreadPoolExecutor(max_workers=4)
40+
results = list(pool1.map(gcd, NUMBERS))
41+
end = time.time()
42+
delta = end - start
43+
print(f'并发执行时间: {delta:.3f} 秒')
44+
45+
## 并行求解
46+
start = time.time()
47+
pool2 = ProcessPoolExecutor(max_workers=4)
48+
results = list(pool2.map(gcd, NUMBERS))
49+
end = time.time()
50+
delta = end - start
51+
print(f'并行执行时间: {delta:.3f} 秒')

0 commit comments

Comments
 (0)