Processing parallel arrays in C #

I have an array of 921600 numbers from 0 to 255.

I need to check each number to see if this threshold is exceeded.

Is it possible to check the first and second half of the array at the same time to reduce the execution time?

What do I mean, is it possible to execute the following two loops in parallel?

for(int i = 0; i < 921600 / 2; i++)
{
    if(arr[i] > 240) counter++;
}

for(int j = 921600 / 2; j < 921600; j++)
{
    if(arr[j] > 240) counter++;
}

Thank you in advance!

+4
source share
3 answers

I suggest using Parallel Linq (PLinq) for this

int[] source = ...

int count = source
  .AsParallel()  // comment this out if you want sequential version
  .Count(item => item > 240);
+9
source

What you ask is strictly possible, as shown below.

int counter = 0;
var tasks = new List<Task>();
var arr = Enumerable.Range(0, 921600).ToArray();
tasks.Add(Task.Factory.StartNew(() =>
{
    for (int i = 0; i < 921600 / 2; i++)
    {
        if (arr[i] > 240) counter++;
    }
}));
tasks.Add(Task.Factory.StartNew(() =>
{
    for (int j = 921600 / 2; j < 921600; j++)
    {
        if (arr[j] > 240) counter++;
    }
}));
Task.WaitAll(tasks.ToArray());

! , - , , , . LinqPad, , 600000 800000. , .

, , . , . ( 0.042 )

int counter = 0;
var tasks = new List<Task>();
var arr = Enumerable.Range(0, 921600).ToArray();
var locker = new Object();
tasks.Add(Task.Factory.StartNew(() =>
{
    for (int i = 0; i < 921600 / 2; i++)
    {
        if (arr[i] > 240)
            lock (locker)
                counter++;
    }
}));
tasks.Add(Task.Factory.StartNew(() =>
{
    for (int j = 921600 / 2; j < 921600; j++)
    {
        if (arr[j] > 240)
            lock (locker)
                counter++;
    }
}));
Task.WaitAll(tasks.ToArray());

Parallel Linq, :

Enumerable.Range(0, 921600).AsParallel().Count(x=>x>240);

0.031, , , - , AsParallel 0.024. . , , .

, / , , .

+2

While google parallel concepts, came across your request. Maybe below a little trick can help you

int n=921600/2;
for(int i=0; i<n; i++)
{
 if(arr[i]>240) counter ++;
 if(arr[n + i] > 240) counter ++;
}
0
source

Source: https://habr.com/ru/post/1676081/


All Articles