Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Vectorized Array Addition

Is there anyway to "vectorize" the addition of elements across arrays in a SIMD fashion?

For example, I would like to turn:

var a = new[] { 1, 2, 3, 4 };
var b = new[] { 1, 2, 3, 4 };
var c = new[] { 1, 2, 3, 4 };
var d = new[] { 1, 2, 3, 4 };

var e = new int[4];

for (int i = 0; i < a.Length; i++)
{
    e[i] = a[i] + b[i] + c[i] + d[i];
}

// e should equal { 4, 8, 12, 16 }

Into something like:

var e = VectorAdd(a,b,c,d);

I know something may exist in the C++ / XNA libraries, but I didn't know if we have it in the standard .Net libraries.

Thanks!

like image 720
Alex Moore Avatar asked Nov 21 '11 16:11

Alex Moore


2 Answers

You will want to look at Mono.Simd:

http://tirania.org/blog/archive/2008/Nov-03.html

It supports SIMD in C#

using Mono.Simd;


//...
var a = new Vector4f( 1, 2, 3, 4 );
var b = new Vector4f( 1, 2, 3, 4 );
var c = new Vector4f( 1, 2, 3, 4 );
var d = new Vector4f( 1, 2, 3, 4 );

var e = a+b+c+d;
like image 103
sehe Avatar answered Sep 28 '22 16:09

sehe


Mono provides a relatively decent SIMD API (as sehe mentions) but if Mono isn't an option I would probably write a C++/CLI interface library to do the heavy lifting. C# works pretty well for most problem sets but if you start getting into high performance code it's best to go to a language that gives you the control to really get dirty with performance.

Here at work we use P/Invoke to call image processing routines written in C++ from C#. P/Invoke has some overhead but if you make very few calls and do a lot of processing on the native side it can be worth it.

like image 37
Ron Warholic Avatar answered Sep 28 '22 16:09

Ron Warholic