Java 17 Recipes


Download 3.2 Mb.
Pdf ko'rish
bet40/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   36   37   38   39   40   41   42   43   ...   245
Bog'liq
Java 17 Recipes

2-10. The Vector API
 Problem
You want a portable API for expressing vector computations.
 Solution
Java 17 introduces an API for vector computations achieving performance superior to 
equivalent scalar computations. The following is standard code for summing two arrays.
Chapter 2 enhanCements from Java 9 through Java 17 


64
static void nonVectorSumInt(int[] arrayOne, int[] arrayTwo, int[] s) {
for (int i = 0; i < arrayOne.length; i++) {
s[i] = (arrayOne[i] + arrayTwo[i]) ;
}
}
The following is the code using vector.
static final VectorSpecies SPECIES = IntVector.SPECIES_PREFERRED;
static void vectorSumInt(int[] arrayOne, int[] arrayTwo, int[] s) {
int i = 0;
int upperBound = SPECIES.loopBound(arrayOne.length);
for (; i < upperBound; i += SPECIES.length()) {
var vIntaOne = IntVector.fromArray(SPECIES, 
arrayOne, i);
var vIntaTwo = IntVector.fromArray(SPECIES, 
arrayTwo, i);
var vs = vIntaOne.add(vIntaTwo);
vs.intoArray(s, i);
}
for (; i < arrayOne.length; i++) {
s[i] = (arrayOne[i] + arrayTwo[i] );
}
}
For testing the provious code, create the main class.
public static void main(String[] args) {
int[] a = new int[]{1, 3, 2, 4};
int[] b = {5, 6, 7, 8};
int[] c = {0, 0, 0, 0};
VectorExample.nonVectorSumInt(a, b, c);
System.out.println("nonVectorSumInt");
for (int i = 0; i < c.length; i++) {
System.out.println(c[i]);
}
Chapter 2 enhanCements from Java 9 through Java 17 


65
VectorExample.vectorSumInt(a, b, c);
System.out.println("vectorSumInt");
for (int i = 0; i < c.length; i++) {
System.out.println(c[i]);
}
}
preferred species is a species of maximal bit size for the platform (i.e., the preferred 
length of vectors supported by the platform). Open a terminal window for compiling and 
executing command lines.
The following is the output.
nonVectorSumInt
6
9
9
12
vectorSumInt
6
9
9
12
 How It Works
You can compile and execute from the terminal window. Use the following command to 
add the jdk.incubator.vector module to the class.

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   36   37   38   39   40   41   42   43   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling