multithreading - Why this python multi-thread approach take more time than single thread to solve the same task? -
why python multi-thread approach take more time single thread solve same problem?
note computer multi-core processor cpu.
i wrote same code in both ways , make comparison. surprisingly single thread way faster! have thoughts?
#!/usr/bin/python l = [1,2,3,4,5,7,8,9,10] def gen(index,value): if index==len(l): return 1 count=0 in range(len(value)+1): count+=gen(index+1,value[:i]+[l[index]]+value[i:]) return count #single thread approach print gen(1,[1]) #this takes 480ms run! #multi-thread approach threading import thread def t1_start(): global pointer1 pointer1=gen(2,[2,1]) def t2_start(): global pointer2 pointer1=gen(2,[1,2]) pointer1=0 pointer2=0 t1=thread(target=t1_start,args=()) t2=thread(target=t2_start,args=()) t1.start() t2.start() t1.join() t2.join() #print pointer1+pointer2 #this takes 650ms run!
i've had problem in java. users suggested overhead, creation of threads costs, slowing down much, took longer. recommend try threaded code really complex calculations , more numbers in gen(index, value) function. threaded code might better simple solution, if gen function take more time.
Comments
Post a Comment