Search code examples
c#arraysmultiplication

Faster Multiplication of double Array values


Hello I have a one dimensional array which represents a two dimensional array. Based on the position of each value will determine the coefficient it is multiplied by.

At the moment I iterate over each value in a for loop, multiply by the correct coefficient and then store the product in another array.

MultiplyEachValue.cs

internal double[] MultiplyEachValue(double[] oneDimArray, int width, int height, Alignment coeffs)
{
    var toReturn = new double[oneDimArray.Length];
    for (int i = 0; i < oneDimArray.Length; i++)
    {
        double curVal;
        if(isEvenPos(i, width, height) == true)
        {
            curVal = coeffs.Small * oneDimArray[i];
        }
        else if (isOddPos(i, 4, 2) == true)
        {
            curVal = coeffs.Large * oneDimArray[i];
        }
        else if (isOppoPos(i, 4, 2) == true)
        {
            curVal = coeffs.Medium * oneDimArray[i];
        }
        else
        {
            curVal = 1;
        }
        toReturn[i] = curVal;
    }
    return toReturn;
}

Any idea how I can make it faster? I have heard of things like dot multiplication but I do not know if it can be applied here. Any suggestions would be great. Thanks!!!


Solution

  • You should run the app with profiling, ideally with a large input so that it takes longer. Then identify hotspots, then review those to see if they can be improved.

    Also be aware that elapsed execution time and CPU consumed time are different things too. Are you seeking to reduce CPU cost or elapsed time?

    You should also order your if/else ladder to test for the most common scenario first, for example if most of the data ends up in the last if test, then making that check the first check will improve things.

    Having said that, the code looks easy to parallelize and on a multi-core machine you could - in principle - see an 'n' factor speed up with 'n' cores if you parallelize the loop.