Reputation: 17455
i am trying to find what is a good measure for using C# 4.0 threaded loop. Let's say I have two arrays now, multidimensional, of width/height 8/5, i.e. 40 elements in each.
Through a piece of code I am optimising at the moment, I come accross such situations a few times, where I am just multipling element by element such two tables (using a nested loop)
Is is worth using 4.0's threaded loop for such thing ? if not, what is a good practice/size estimates for using it or not ?
Kind regards,
Upvotes: 1
Views: 297
Reputation: 36082
The challenge with multithreading a nested loop is separating the work and data into independent pools. If your loop modifies the arrays as it progresses through them, this will not work well when split out to multiple threads. If you already have your loops set up so that the input data is read-only, and the output of the loop goes into a different data structure, then there is hope for multithreading. Read-only input + localized output is good for multithreading.
There is also the matter of how much work is happening in each loop iteration. You won't get much benefit from multithreading a loop that does very little per iteration. Most of the wall-clock time in a small fast loop will be spent on loop management, not on the work itself, and making the loop multithreaded will only increase the loop management overhead. If your loop is doing a non-trivial amount of work per iteration, you have a better chance of seeing a benefit from multithreading.
If the per iteration work includes blocking operations such as file I/O, you might think that multithreading the loop will improve things. In many cases, multithreading a file I/O bound loop will only make things worse. The hardware device at the other end of those file I/Os usually can't move the physical read/write head any faster so asking for it to do more things at the same time isn't going to do any good. You'd probably be better off to investigate using async file I/O before trying to multithread the loop.
Finally, don't do any of this based on guessing where multithreading might help. Measure the performance of the code before multithreading and after. If you can't find a situation where multithreading makes a significant improvement, then don't do it. It's not worth the additional effort and risks just to get a marginal improvement sometimes.
Upvotes: 5