《再談python的gil》這篇檔案中漏掉了乙個很重要的函式沒有討論到:sys.setcheckinterval
該函式用於設定gil自動切換的間隔,預設值為100,之前的測試都是在預設值下得出來的結果,接下來我們來再通過例子做個實驗,將checkinterval設定成1000,看下是什麼情況
3.1 測試用例:
from threading import thread
from threading import event as tevent
from multiprocessing import process
from multiprocessing import event as pevent
from timeit import timer
import sys
sys.setcheckinterval(1000) #(100000)
def countdown(n,event):
while n > 0:
n -= 1
event.set()
def io_op(n,event,filename):
f = open(filename,'w')
while not event.is_set():
f.write('hello,world')
f.close()
def t1():
count=100000000
event = tevent()
thread1 = thread(target=countdown,args=(count,event))
thread1.start()
thread1.join()
def t2():
count=100000000
event = tevent()
thread1 = thread(target=countdown,args=(count//2,event))
thread2 = thread(target=countdown,args=(count//2,event))
thread1.start(); thread2.start()
thread1.join(); thread2.join()
def t3():
count=100000000
event = pevent()
p1 = process(target=countdown,args=(count//2,event))
p2 = process(target=countdown,args=(count//2,event))
p1.start(); p2.start()
p1.join(); p2.join()
def t4():
count=100000000 #00000
event = tevent()
thread1 = thread(target=countdown,args=(count,event))
thread2 = thread(target=io_op,args=(count,event,'thread.txt'))
thread1.start(); thread2.start()
thread1.join(); thread2.join()
def t5():
count=100000000 #00000
event = pevent()
p1 = process(target=countdown,args=(count,event))
p2 = process(target=io_op,args=(count,event,'process.txt'))
p1.start(); p2.start()
p1.join(); p2.join()
if __name__ == '__main__':
t = timer(t1)
print('countdown in one thread:%f'%(t.timeit(1),))
t = timer(t2)
print('countdown use two thread:%f'%(t.timeit(1),))
t = timer(t3)
print('countdown use two process:%f'%(t.timeit(1),))
t = timer(t4)
print('countdown in one thread with io op in another thread:%f'%(t.timeit(1),))
t = timer(t5)
print('countdown in one process with io op in another process:%f'%(t.timeit(1),))
輸出:countdown in one thread:7.867444
countdown use two thread:9.830585
countdown use two process:2.148110
countdown in one thread with io op in another thread:7.691811
countdown in one process with io op in another process:7.477607結論:
是的,countdown在多執行緒情況下的效率得到了極大的提公升,原因就執行緒的有效執行率大大提高了,當切換到執行緒時,執行緒得以執行的機會提高了。
但是這會導致i/o的效能大大的降低。thread.txt的大小為2161kb,而process.txt的大小則為22401kb
而在checkinterval值為預設值100時則thread.txt和process.txt的大小相當。
(完)
程序 執行緒 python的GIL
由於計算機資源有限,程式競爭計算機資源 程序 競爭計算機資源的基本單位,至少有乙個程序 單核cpu只能執行乙個程式?在不同的應用程式程序之間切換 多核 4核8核 程序排程演算法 乙個程式被掛起切換到另乙個程式 程序 執行緒 切換開銷使非常大的 cpu利用率降低,一些cpu的資源消耗到程序切換中 執行...
Python 學習筆記 GIL
python 全域性翻譯鎖 gil global interpreter lock 為了實現在多核環境下的執行時資料的一致性,python採用加鎖的思想來實現這種同步和一致性,這把鎖就是gil。這造成了一定量的效能損失,使用鎖的原因是因為python直譯器內部是執行緒不安全的。另外一點,首先需要明確...
python 執行緒GIL鎖
gil global interpreter lock cpython python中乙個執行緒對應於c語言中的乙個執行緒 gil使得同乙個時刻只有乙個執行緒在乙個cpu上執行位元組碼,無法將多個執行緒對映到多個cpu上執行 gil會根據執行的位元組碼行數以及時間片釋放gil,gil在遇到io的操作...