Thread,Process,Line
在編程人生中,一定會遇到計算時間過長的問題,這個時候提高算法效率就成了必然。有幾種方法:算法優化、激發CPUGPU的力量等。
我現在分享關於python多線程多進程的方式和心得,用於激發電腦性能。
Thread
from threading import Thread
任何優化方式都有自己的侷限性,python3由於GIL鎖機制的問題,在多線程方面對於一大部分情況效果不好。但是對於網絡編程方面,多線程卻是一個非常好的優化手段!注意上述一句話!!!!!!!!!!!!
多線程使用過程中,打開任務管理器可以看到大量內存被消耗。
使用方式:
temp=Thread(target=function,args)
temp.start()
Process
from multiprocessing import Process
多線程是一張桌子好幾個人圍着坐,多進程則是好多張桌子大家一起坐。顯然多進程取決於電腦CPU的性能,也就是核數。使用過程中,打開任務管理器可以看到CPU處於100%狀態。
使用方式:
temp=Process(target=function,args)
temp.start()
Line
常見的順序執行代碼
比較三者
爲了更直觀地體會到三者的區別和優勢,舉個例子,從結果中感受差別。
# 三種測試函數
#(1)定義CPU密集計算函數
def count(x,y):
#使程序完成150萬次計算
c=0
while c<500000:
c+=1
x+=1
y+=1
#(2)定義IO密集的文件讀寫函數
def write():
f=open('test.txt','w')
for x in range(500000):
f.write("testwrite\n")
f.close()
def read():
f=open('test.txt','r')
f.readlines()
f.close()
def io():
write()
read()
#(3)定義網絡請求函數
#head
head={}
head['User-Agent']=r'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36'
#url
url=r"http://www.tieba.com"
def http_request():
try:
webPage=requests.get(url,head)
html=webPage.text
return {"context":html}
except Exception as e:
return {"error":e}
注意理解CPU密集運算、IO密集運算和網絡運算的意義,這三者對應了大多數的項目需求。
爲了減少代碼量,定義測試函數,可以理解爲泛型編程的思想。
#(x)定義測試函數
def test(testname='Thread',number=10,way=Thread,function=None,args=()):
counts=[]
t=time.time()
#保證默認值
if function==None:
def die():
i=1000
return i
function=die
pass
#開啓多線程或多進程
for x in range(number):
temp=way(target=function,args=args)
counts.append(temp)
temp.start()
#等待算法停止,注意這是比較不好的方式,可以用強制殺死
e=counts.__len__()
while e:
for th in counts:
if not th.is_alive():
counts.remove(th)
e=counts.__len__()
#打印出算法運行時間
print("%s %s : %s"%(way.__name__,testname,(time.time()-t)))
準備工作完成,開始測試
#(5)測試線性執行IO密集操作、CPU密集操作所需時間、網絡請求密集型操作所需時間
if __name__=='__main__':
#IO密集型操作
t=time.time()
for x in range(50):
io()
print("line IO: %s"%(time.time()-t))
#CPU密集型操作
t=time.time()
for x in range(50):
count(1,1)
print("line CPU: %s"%(time.time()-t))
#網絡請求密集型操作
t=time.time()
for x in range(50):
http_request()
print("line http Request: %s"%(time.time()-t))
pass
#(6)測試多線程執行IO密集操作、CPU密集操作所需時間、網絡請求密集型操作所需時間
if __name__=='__main__':
test('CPU',50,function=count,way=Thread,args=(1,1))
test('IO',50,function=io,way=Thread)
test('http request',50,way=Thread,function=http_request)
pass
#(7)測試多進程執行IO密集操作、CPU密集操作所需時間、網絡請求密集型操作所需時間
if __name__=='__main__':
test("CPU",50,Process,count,(1,1))
test("IO",50,Process,io)
test("http request",50,way=Process,function=http_request)
os.remove("test.txt")
pass
結果對比
line IO: 19.93960452079773
line CPU: 4.375457525253296
line http Request: 17.290654182434082
Thread IO : 19.752081871032715
Thread CPU : 4.031674861907959
Thread http request : 1.578291654586792
Process IO : 6.2662858963012695
Process CPU : 3.2815961837768555
Process http request : 8.39150881767273
很顯然,可以看到python多線程在網絡請求方面的優勢,同時多進程在IO、CPU方面的特點。唯物主義辯證思想告訴我們具體問題具體分析~~~所以我們在學會上述方式後,根據項目需求選擇合理的解決方式,那會變得非常有趣!
丁。