當前位置:成語大全網 - 新華字典 - Python實驗:采用多線程在壹個文件中查找特定字符串

Python實驗:采用多線程在壹個文件中查找特定字符串

import?threading?,?time

def?countstr(f):

global?findstr,occurtimes

times=0

for?string?in?f:

if?findstr?in?string:

times+=1

occurtimes.append(times)

occurtimes=[]

threadnum=int(raw_input("please?input?thread?number:"))

filename=raw_input("please?input?filename:")

findstr=raw_input("please?input?to?find?string:")

text=open(filename).readlines()

start=time.time()

threads=[]

for?i?in?range(threadnum):

t=threading.Thread(target=countstr,args=(text[i::threadnum],))

threads.append(t)

t.start()

for?t?in?threads:

t.join()

end=time.time()

print("multithread?using?%.5f?seocnds"%(end-start))

print('string?"%s"?occurs?%d?times'%(findstr,sum(occurtimes)))

print

occurtimes=[]

start=time.time()

countstr(text)

end=time.time()

print("singlethread?uing?%.5f?seconds"%(end-start))

print('string?"%s"?occurs?%d?times'%(findstr,sum(occurtimes)))