Mo Valipour
Mo Valipour

Reputation: 13496

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

I have a structure (class) that 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?

Upvotes: 4

Views: 4295

Answers (4)

Henk Holterman
Henk Holterman

Reputation: 273244

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);

Upvotes: 3

George Mamaladze
George Mamaladze

Reputation: 7931

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;});

Upvotes: 1

Sebastian Mach
Sebastian Mach

Reputation: 39089

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))).

Upvotes: 1

Jess
Jess

Reputation: 3049

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.

Upvotes: 0

Related Questions