[英]why my Multi-threading code spend More time than Single-threading code
這是我的代碼:
import re,threading
class key_value:
def __init__(self,filename='a.txt'):
self.filename = filename
def __getitem__(self,key):
file = open(self.filename,'r')
data = file.read()
value = re.findall(r''+str(key)+' - (\S+)',data)
return value
def __setitem__(self,key,value):
data = open(self.filename).read()
b = re.split(r'('+str(key)+' - )\S*', data)
#
if len(b) == 1:
result = str(key)+' - '+str(value)
result += '\n'
file = open(self.filename,'a')
file.write(result)
return
elif type(value) == type([]):
result = "".join(str(x) + value.pop(0) if x == str(key)+' - ' else x for x in b)
else :
result = "".join(str(x) + str(value) if str(x) == str(key)+' - ' else x for x in b)
file = open(self.filename,'w')
file.write(result)
def run(self):
print 'the thread is running!!'
class do_thread(threading.Thread):
def __init__(self,filename='a.txt',key=None,value=None):
threading.Thread.__init__(self)
self.filename = filename
self.key=key
self.value=value
def run(self):
print 'the thread is running!!'
a = key_value(self.filename)
if(self.key and self.value):
a[self.key] = self.value
elif(self.key):
self.value = a[self.key]
#'''#Multi-threading code
for i in range(1000):
a = do_thread(key=i,value=i)
#print 'the main programme'
a.start()
#a.join()
#print 'game over'
'''# Single-threaded code
for i in range(1000):
a = key_value()
a[i] = i
'''
我的老板告訴我在代碼中添加多線程,
我添加了它,但是我發現多線程花費更多的時間,
那么老板說的多線程有什么用,
謝謝
CPython(主要的Python實現)不是多線程的。 GIL擋住了路。 因此,您只有兩個線程在一個內核上運行(即,它們不是並行運行),但是在所有上下文切換和線程必須擁有的其他開銷上。 不過請注意:
編輯:從評論看來,您的計算機仍然無法進行多線程處理。 好吧,以上仍然成立。
該應用程序是IO綁定的,而不是CPU綁定的,因此多線程將無濟於事。
同樣,如前所述,1,000個線程將不會產生生產力,請嘗試使用較小的數字,即2-4,最多嘗試使用大約2×內核數 。 線程數量增加得過多會導致線程管理的開銷,從而導致應用程序的運行速度大大降低。
當您必須同時訪問不同的資源(文件,網絡,用戶界面...)時,多線程既有用又高效。 在您的代碼中,對我而言,您似乎只能訪問一個資源(一個文件),因此mutlti線程的效率較低
我沒有詳細閱讀您的代碼,但在多核計算機上對其進行了測試,您可能會看到一個改進。
原因之一是由於讀取開銷,一次訪問一個文件實際上比同時訪問多個文件快得多。 (您知道磁盤的緩存有限,始終最好從頭到尾讀取文件作為流)。
無論如何,瓶頸是磁盤。 您需要更多資源,這是最糟糕的情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.