I basically have to obtain a certain probability distribution by sampling from a sample of 5000 matrices. So I just need to count how many times element X occurs in the position (i,j) of these 5000 matrices. Then, I save these [values and counts] in a dictionary.
That said, I thought it could be a good idea to parallelize my code, as a serial code would run incredibly slow. The code is the following:
import multiprocessing as mp
import numpy as np
def func(N):
d = {}
filenames = ["file" + str(k) + ".txt" for k in range(N, N + 1000)]
##each of these files is a 306x306 matrix
for i in range(306):
data = np.vstack([np.loadtxt(f, delimiter=",", usecols=i) for f in filenames])
for j in range(306):
values, counts = np.unique(data.T[j], return_counts=True)
for i in values:
d[i] = counts[np.where(values == i)]
return d
if __name__ == "__main__":
N = mp.cpu_count()
with mp.Pool(processes=N) as p:
results = p.map(func, [m for m in range(1000, 5000, 1000)])
Since it is my first time parallelizing a function, I would like some feedback. Also, as this is still slow due to the fact that it has to load a 1000x306 matrix, any advice on how to improve it would be very welcome.