Last active
January 7, 2020 04:38
-
-
Save kishida/51b3dca5d38c6d2520336bd1fe04419f to your computer and use it in GitHub Desktop.
Vector API sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import jdk.incubator.vector.*; | |
import java.util.Random; | |
public class Main { | |
public static void main(String... args) { | |
int count = 1000_000; | |
float a[] = new float[count]; | |
float b[] = new float[count]; | |
float c[] = new float[count]; | |
Random r = new Random(); | |
for (int i = 0; i < count; ++i) { | |
a[i] = r.nextFloat(); | |
b[i] = r.nextFloat(); | |
} | |
for (int i = 0; i < 10; ++i) { | |
sqrtsum(a, b,c); | |
sqrtsumVector(a, b,c); | |
} | |
long s = System.nanoTime(); | |
for (int i = 0; i < 100; ++i) { | |
sqrtsum(a, b,c); | |
} | |
long m = System.nanoTime(); | |
System.out.println(m - s); | |
for (int i = 0; i < 100; ++i) { | |
sqrtsumVector(a, b,c); | |
} | |
System.out.println(System.nanoTime() - m); | |
} | |
static void sqrtsum(float[] a, float[] b, float[] c) { | |
for (int i = 0; i < a.length; ++i) { | |
c[i] = -(a[i] * a[i] + b[i] * b[i]); | |
} | |
} | |
static VectorSpecies<Float> SPECIES = FloatVector.SPECIES_256; | |
static void sqrtsumVector(float[] a, float[] b, float[] c) { | |
int i = 0; | |
int len = a.length & ~(SPECIES.length() - 1); | |
for (; i < len; i+= SPECIES.length()) { | |
//var m = SPECIES.indexInRange(i, a.length); | |
var va = FloatVector.fromArray(SPECIES, a, i); | |
var vb = FloatVector.fromArray(SPECIES, b, i); | |
var 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]) * -1f; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment