Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Faster way to manipulate mutli byte array

Tags:

arrays

c#

I have this:

var data = new byte[100,100,1];

//data is populated from external source

for (var h = 0; h < 100 ; h++)
{
    for (var w = 0; w < 100; w++)
    {
        if (Data[h, w, 0] > 10)
        {
            Data[h, w, 0] = 255;
        }
    }
}

and I am just saying if the value is above 10 then change it to 255.

But, it is quite slow.

Is there a quicker way to do the above?

like image 952
Andrew Simpson Avatar asked Nov 29 '18 09:11

Andrew Simpson


2 Answers

You could also mix this with unsafe and Pointers. However, you need to jump through a couple of more hoops. It should give you a bit performance in release mode with pointers

// p is because you cant used fixed in a lambda
public static unsafe byte* p;

// AggressiveInlining to compile in line if possible
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void DoOp(int i)
{
   if (*(p + i) > 10) *(p + i) = 255;
}

public static unsafe void Main()
{
   int x = 10, y = 10, z = 1;  
   var data = new byte[x, y, z];

   fixed (byte* pbytes = data)
   {
      p = pbytes;
      Parallel.For(0, x * y,
         new ParallelOptions() { MaxDegreeOfParallelism = Environment.ProcessorCount},
         DoOp);
   }
}
like image 196
TheGeneral Avatar answered Nov 17 '22 08:11

TheGeneral


You can perform parallel operation for outer for loop so as to increase performance.

 var Data = new byte[100,100,1];
 //data is populated from external source

 // Parallelize the outer loop for h 
 Parallel.For(0, 100, h=>
 {
    for (var w = 0; w < 100; w++)
    {
        if (Data[h, w, 0] > 10)
        {
            Data[h, w, 0] = 255;
        }
    }
 });

Note: you must include using System.Threading.Tasks; in your source code.

like image 20
BishalG Avatar answered Nov 17 '22 07:11

BishalG