CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
jackfrued

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: jackfrued/Python-100-Days
Path: blob/master/Day16-20/code/example22.py
Views: 729
1
"""
2
多进程和进程池的使用
3
多线程因为GIL的存在不能够发挥CPU的多核特性
4
对于计算密集型任务应该考虑使用多进程
5
time python3 example22.py
6
real 0m11.512s
7
user 0m39.319s
8
sys 0m0.169s
9
"""
10
import concurrent.futures
11
import math
12
13
PRIMES = [
14
1116281,
15
1297337,
16
104395303,
17
472882027,
18
533000389,
19
817504243,
20
982451653,
21
112272535095293,
22
112582705942171,
23
112272535095293,
24
115280095190773,
25
115797848077099,
26
1099726899285419
27
] * 5
28
29
30
def is_prime(n):
31
"""判断素数"""
32
if n % 2 == 0:
33
return False
34
35
sqrt_n = int(math.floor(math.sqrt(n)))
36
for i in range(3, sqrt_n + 1, 2):
37
if n % i == 0:
38
return False
39
return True
40
41
42
def main():
43
"""主函数"""
44
with concurrent.futures.ProcessPoolExecutor() as executor:
45
for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
46
print('%d is prime: %s' % (number, prime))
47
48
49
if __name__ == '__main__':
50
main()
51
52