I am fairly new to asynchronous programming; I am developing a program that deals with numbers in different bases and I want to make the addition method asynchronous.
Firstly, it computes the linear convolution and does the carrying later, thus every iteration of the for-loop is independent (Example):
(Little Endianness btw) [2,7,1] + [8,7,5] = [10,14,6] => [0,5,7]
The question is, can I, if there are threads available, make the addition process faster by having the iterations done at the same time in different threads, and how?
>Solution :
In case of huge arrays (threading has its own overhead), you can try Parallel, e.g. Parallel.For:
int[] left = ...
int[] right = ...
int[] result = new int[left.Length];
...
Parallel.For(0, left.Length, i => result[i] = left[i] + right[i]);
Let’s have a look on the effect:
int N = 100_000_000;
int[] left = new int[N];
int[] right = new int[N];
int[] result = new int[left.Length];
// To prevent garbage collection while testing
GC.Collect(2);
Stopwatch sw = new Stopwatch();
sw.Start();
// Parallel version
//Parallel.For(0, left.Length, i => result[i] = left[i] + right[i]);
// Standard for loop version
for (int i = left.Length - 1; i >= 0; --i)
result[i] = left[i] + right[i];
sw.Stop();
Console.Write(sw.ElapsedMilliseconds);
Outcome (.Net 6 IA-64, Realease build, Core i9, 6 cores)
200 - parallel version
500 - for loop version