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?
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);
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With