开发者

What is a high performance way of multiplying/Adding a big array of numbers with a constant in c#?

开发者 https://www.devze.com 2023-03-20 21:54 出处:网络
I have a structure (class) tha开发者_如何学Got keeps very large number of numbers (either float, double, int, byte) in an array.

I have a structure (class) tha开发者_如何学Got keeps very large number of numbers (either float, double, int, byte) in an array.

Now I want to have very high performance approach to apply some primitive operations (Add/Subtract/Divide/Multiply with a constant) on this array.

This arrays is on a continuous piece of memory so for example for copying it I am using Buffer.BlockCopy.

But what about adding a constant or multiplying with a constant?

The first choice is to walk through the array using pointers. What other approaches do you suggest for this?


Using pointer (unsafe) is not certain to be more performant.

Why don't you start with a normal for(int index = 0; index < data.Lenght; index++) loop and see if it meets your requirements.


And of course, the next step would be processing in parallel :

 Parallel.For(0, data.Length, i => data[i] *= myFactor);


Pointers won't help you much. Two approaches that could/should be combined:

  • Process multiple numbers in parallel using some SIMD approach, SSE being one instance of it
  • Process different array chunks in different threads ("multithreading"); this is most worthwhile on machines with more than CPU core

If you want to reduce ("reduction") the result, e.g. say you want to build the sum of all elements, you could also divide the chunks recursively, and build sums of sums (of sums (of sums (you get the point))).


This multiplies every element with 5 and writes back into the same array.

        var someArray = new int[] {1, 2, 3, 4, 5, 6, 7};
        int i=0;
        Array.ForEach(someArray, (x) => {someArray[i++] = x * 5;});


I don't think you will find a general solution faster than just walking through the array. Most processors will prefetch items in your array; thus as long as your manipulations are small, you'll obtain optimum performance by just accessing each item consecutively.

Keep work per item as straighforward as possible and minimize assignments and fetches inside the loop. Keep as much work as you can outside the loop.

0

精彩评论

暂无评论...
验证码 换一张
取 消