Why Java SIMD (Panama) is slower than scalar?

2.1k Views Asked by At

I have followed the intel tutoriel for SIMD in Java with Panama. I want to do some simple operations on arrays:

Here the scalar and vector loop from the website :

public static void scalarComputation(float[] a, float[] b, float[] c) {
    for (int i = 0; i < a.length; i++) {
        c[i] = (a[i] * a[i] + b[i] * b[i]) * - 1.0f;
    }
}

public static void vectorComputation(float[] a, float[] b, float[] c) {
    int i = 0;
    for (; i < (a.length & ~(species.length() - 1));
         i += species.length()) {
        FloatVector<Shapes.S256Bit> va = speciesFloat.fromArray(a, i);
        FloatVector<Shapes.S256Bit> vb = speciesFloat.fromArray(b, i);
        FloatVector<Shapes.S256Bit> vc = va.mul(va).
                add(vb.mul(vb)).
                neg();
        vc.intoArray(c, i);
    }

    for (; i < a.length; i++) {
        c[i] = (a[i] * a[i] + b[i] * b[i]) * -1.0f;
    }
}

When I measure the time :

float [] A = new float[N];
float [] B = new float[N];
float [] C = new float[N];

for(int i = 0; i < C.length; i++)
{
    C[i] = 2.0f;
    A[i] = 2.0f;
    B[i] = 2.0f;
}

long start = System.nanoTime();
for(int i = 0; i < 200; i++)
{
    //scalarComputation(C,A,B);
    //vectorComputation(C,A,B);
}
long end = System.nanoTime();        
System.out.println(end - start);

I always get a higher time for vector than scalar. Do you have an idea why? Thank you.

1

There are 1 best solutions below

1
On

You are using the wrong branch: build from the vectorIntrinsics branch. You also need to use JMH to get proper measurements - here are some third party benchmarks written for the Vector API.

For the difference the Vector API makes to a dot product calculation, see here.