Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

python - Shared memory parallelization

I have a vector v with size n and I need to increment by 1 each entry using this code:

 for output_diff in results:
     for i in n:
         if (output_diff & (1 << i)):
             v[i] += 1

Size of results is approximately 10 000 000 and size of n = 4096. How can I do that using parallelism or maybe multiprocessing in python? I tried using the idea in How to implement a reduce operation in python multiprocessing? , but it takes longer than serial way.

question from:https://stackoverflow.com/questions/65852882/shared-memory-parallelization

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If your operation is taking a long time (say maybe 30 seconds or longer), then you could perhaps benefit from dividing results into as many pieces as you want to run python processes, and using python's multiprocessing module. If the operation isn't taking that long, the overhead of starting these new processes will outweigh the benefit of using them.

Since the operation being carried out does not depend on the values stored in v, each process can write to an independent vector and you can aggregate the results at the end. Pass each process a vector v_prime of 0's of the same length as v. Perform the above operation, each process handling a portion of the output_diffs in results and incrementing the corresponding values in v_prime instead of v. Then at the end, each process returns its vector v_prime. Sum all of the returned v_primes and the original v (this is where having the items expressed as numpy arrays is helpful, as it is easy to add numpy vectors of the same length) to get the correct result.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...