I am using multiprocessing for training a neural network where one process construct the batch samples and puts them in a queue and the parent process reads from the queue and trains the network with pytorch.
I noticed that the total time of training using multiprocessing was not shorter than using a single process, and when investigating further, I discovered that although reading from the queue in the multiprocess is faster than constructing the queue in the single process (as expected), the process of training (which is the same code for both multiprocessing and single processing) takes longer in the multiprocess.
I made up a simple script exemplifying. See script below:
import multiprocessing as mp
import numpy as np
import time
n = 200
def get_sample():
local_loop = 400
# data
x = np.random.rand(n,n)
p = np.random.rand(n,n)
y = 0
for i in range(local_loop):
y += np.power(x, p)
return y
def new_process(q_data, total_loops):
for i in range(total_loops):
q_data.put(get_sample())
print('finish new process')
def main(multi_proc=False):
st = time.time()
total_loops = 100
local_loop = 2500
mt = 0
other_t = 0
st_multi = time.time()
if multi_proc:
q_data = mp.Queue()
new_proc = mp.Process(target=new_process,args=(q_data, total_loops))
new_proc.start()
mt += time.time() - st_multi
for i in range(total_loops):
st_multi = time.time()
if multi_proc:
y = q_data.get()
else:
y = get_sample()
mt += time.time() - st_multi
other_st = time.time()
for j in range(local_loop):
y += np.random.rand(n,n)
other_t += time.time() - other_st
st_multi = time.time()
if multi_proc:
assert q_data.empty()
new_proc.join()
mt += time.time() - st_multi
print('\nmulti_proc', multi_proc)
print('multi_proc_time', mt)
print('other_time', other_t)
print(f'total time: {time.time()-st}')
if __name__ == '__main__':
main(multi_proc=False)
main(multi_proc=True)
When I run it, I get the result:
multi_proc False
multi_proc_time 36.44150114059448
other_time 39.08155846595764
total time: 75.5232412815094
finish new process
multi_proc True
multi_proc_time 0.4313678741455078
other_time 40.54900646209717
total time: 40.980711460113525
other_time is more than 1 second longer when multi_process=True (when they should be the same). This seems to be consistent across platforms/multiple experiments and in my real example it is longer than the gain from using multiprocessing, which is causing a big problem.
Any hint of what is happening?