from threading import Thread
from multiprocessing import Process, Queue
import time
def do_work(start, end, result):
sum = 0
for i in range(start,end):
sum += i
result.append(sum)
return
if __name__=='__main__':
s_time = time.time()
START, END = 0, 80000000
result = list()
th1 = Thread(target=do_work, args=(START, END, result))
th1.start()
th1.join()
print ('Result : ',sum(result),'time =',time.time()-s_time)
def multi_thread(thread_n=1):
start_time = time.time()
START, END = 0, 80000000
result = list()
end_time = end.time()
import multiprocessing.dummy as mp
def do_print(s):
print s
if __name__=="__main__":
p=mp.Pool(4)
p.map(do_print,range(0,10)) # range(0,1000) if you want to replicate your example
p.close()
p.join()
s_time = time.time()
START, END = 0, 80000000
result = list()
th1 = Thread(target=do_work, args=(START, END, result))
th1.start()
th1.join()
print ('Result : ',sum(result),'time =',time.time()-s_time)
Result : 3199999960000000 time = 4.5752880573272705
s_time = time.time()
START, END = 0, 80000000
result = list()
th1 = Thread(target=do_work, args=(START, 20000000, result))
th2 = Thread(target=do_work, args=(20000000, 40000000, result))
th3 = Thread(target=do_work, args=(40000000, 60000000, result))
th4 = Thread(target=do_work, args=(60000000, 80000000, result))
th1.start()
th2.start()
th3.start()
th4.start()
th1.join()
th2.join()
th3.join()
th4.join()
print('Result : ',sum(result),'time =',time.time()-s_time)
Result : 3199999960000000 time = 5.104726076126099
s_time = time.time()
START, END = 0, 80000000
# result = Queue()
result = list()
pr1 = Process(target=do_work, args=(START, 20000000, result))
pr2 = Process(target=do_work, args=(20000000, 40000000, result))
pr3 = Process(target=do_work, args=(40000000, 60000000, result))
pr4 = Process(target=do_work, args=(60000000, 80000000, result))
pr1.start()
pr2.start()
pr3.start()
pr4.start()
pr1.join()
pr2.join()
pr3.join()
pr4.join()
# result.put('STOP')
# sum = 0
# while True:
# tmp = result.get()
# if tmp == 'STOP' : break
# else: sum += tmp
print('Result : ',sum(result),'time =',time.time()-s_time)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-13-ee257784113f> in <module>() 21 # if tmp == 'STOP' : break 22 # else: sum += tmp ---> 23 print('Result : ',sum(result),'time =',time.time()-s_time) TypeError: 'int' object is not callable
from multiprocessing import Process
import os
def info(title):
print(title)
print('parent process:', os.getppid())
print('process id:', os.getpid())
def f(name):
info('function f')
print('hello', name)
# if __name__ == '__main__':
info('main line')
p = Process(target=f, args=('bob',))
p.start()
p.join()
main line parent process: 11614 process id: 11622 function f parent process: 11622 process id: 13423 hello bob