fpe
fpe

Reputation: 2750

array times scalar: loop unrolling

within a JAVA project of mine I must generally multiply huge arrays with scalars. Therefore I was thinking to write a method by employing the so-called loop unrolling. So far I have come up with this:

public static float[] arrayTimesScalar(float[] array, float scalar){
int n = array.length;
float[] result = new float[n];
int m = n % 7;
if(n == 0){ throw new Error("The input array must,at least, hold one element"); }

if (n < 7){
    for(int i = 0; i < 7; i++){
        result[i] = scalar*array[i];
    } // end for
}
else{
    if (m != 0){
        for(int i = 0; i < m; i++){
            result[i] = scalar*array[i];
        }
        for(int i = m; i < n; i += 7){
            result[i] = scalar*array[i];
            result[i + 1] = scalar*array[i + 1];
            result[i + 2] = scalar*array[i + 2];
            result[i + 3] = scalar*array[i + 3];
            result[i + 4] = scalar*array[i + 4];
            result[i + 5] = scalar*array[i + 5];
            result[i + 6] = scalar*array[i + 6];
        }
    }
    else{
        for(int i = 0; i < n; i += 7){
            result[i] = scalar*array[i];
            result[i + 1] = scalar*array[i + 1];
            result[i + 2] = scalar*array[i + 2];
            result[i + 3] = scalar*array[i + 3];
            result[i + 4] = scalar*array[i + 4];
            result[i + 5] = scalar*array[i + 5];
            result[i + 6] = scalar*array[i + 6];
        }
    }
}       
return result;

}

I'd really appreciate understanding if the method is correct at appears now and if it yet makes any sense using loop unrolling, although higly optimized compilers.

Upvotes: 0

Views: 152

Answers (2)

ssindelar
ssindelar

Reputation: 2843

Depending on how large your n is and how hard the time constraints, you could parallelize the multiplication to safe some time. But that is of course a huge change, but I think such high-level changes are the only option to improve performance.

"Trivial" things like loop unrolling are done by the Compiler and the JIT while runtime.

Upvotes: 0

Marko Topolnik
Marko Topolnik

Reputation: 200296

Loop unrolling is such a low-level optimization that it most probably doesn't make sense on modern JVM's. However, you shouldn't guess or ask others: you should test your code on your target system and measure the performance.

As for correctness, I believe this is very easy to verify as well, by writing unit tests, for example. There is nothing obviously wrong with your code.

Upvotes: 2

Related Questions