1、概述
在Python中,計算密集型任務適用于多進程,IO密集型任務適用于多線程
正常來講,多線程要比多進程效率更高,因為進程間的切換需要的資源和開銷更大,而線程相對更小,但是我們使用的Python
大多數的解釋器是Cpython
,眾所周知Cpython
有個GIL鎖
,導致執行計算密集型
任務時多線程實際只能是單線程
,而且由于線程之間切換的開銷導致多線程往往比實際的單線程還要慢,所以在 python 中計算密集型任務通常使用多進程,因為各個進程有各自獨立的GIL,互不干擾。
而在IO密集型
任務中,CPU時常處于等待狀態,操作系統需要頻繁與外界環境進行交互,如讀寫文件,在網絡間通信等。在這期間GIL會被釋放,因而就可以使用真正的多線程。
上面都是理論,接下來實戰看看實際效果是否符合理論
2、代碼練習
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
|
"""多線程多進程模擬執行效率""" from multiprocessing import Pool from threading import Thread import time, math def simulation_IO(a): """模擬IO操作""" time.sleep( 3 ) def simulation_compute(a): """模擬計算密集型任務""" for i in range ( int ( 1e7 )): math.sin( 40 ) + math.cos( 40 ) return def normal_func(func): """普通方法執行效率""" for i in range ( 6 ): func(i) return def mp(func): """進程池中的map方法""" with Pool(processes = 6 ) as p: res = p. map (func, list ( range ( 6 ))) return def asy(func): """進程池中的異步執行""" with Pool(processes = 6 ) as p: result = [] for j in range ( 6 ): a = p.apply_async(func, args = (j, )) result.append(a) res = [j.get() for j in result] def thread(func): """多線程方法""" threads = [] for j in range ( 6 ): t = Thread(target = func, args = (j, )) threads.append(t) t.start() for t in threads: t.join() def showtime(f, func, name): """ 計算并展示函數的運行時間 :param f: 多進程和多線程的方法 :param func: 多進程和多線程方法中需要傳入的函數 :param name: 方法的名字 :return: """ start_time = time.time() f(func) print (f "{name} time: {time.time() - start_time:.4f}s" ) def main(func): """ 運行程序的主函數 :param func: 傳入需要計算時間的函數名 """ showtime(normal_func, func, "normal" ) print () print ( "------ 多進程 ------" ) showtime(mp, func, "map" ) showtime(asy, func, "async" ) print () print ( "----- 多線程 -----" ) showtime(thread, func, "thread" ) if __name__ = = "__main__" : print ( "------------ 計算密集型 ------------" ) func = simulation_compute main(func) print () print () print () print ( "------------ IO 密集型 ------------" ) func = simulation_IO main(func) |
3、運行結果
線性執行 | 多進程(map) | 多進程(async) | 多線程 | |
---|---|---|---|---|
計算密集型 | 16.0284s | 3.5236s | 3.4367s | 15.2142s |
IO密集型 | 18.0201s | 3.0945s | 3.0809s | 3.0041s |
從表格中很明顯的可以看出:
- 計算密集型任務的速度:多進程 >多線程> 單進程/線程
- IO密集型任務速度: 多線程 > 多進程 > 單進程/線程。
所以,針對計算密集型任務使用多進程,針對IO密集型任務使用多線程
到此這篇關于python 多線程與多進程效率測試 的文章就介紹到這了,更多相關python 多線程內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://www.cnblogs.com/jiakecong/p/14690762.html