Skip to content

Instantly share code, notes, and snippets.

@Harshal96
Created June 23, 2019 18:20
Show Gist options
  • Select an option

  • Save Harshal96/36f25b17cafaf999b8a25ccb2d4a249d to your computer and use it in GitHub Desktop.

Select an option

Save Harshal96/36f25b17cafaf999b8a25ccb2d4a249d to your computer and use it in GitHub Desktop.
Branch Prediction Example Java
import java.util.Arrays;
import java.util.Random;
public class Main {
public static void main(String[] args) {
// Generate data
int arraySize = 32768;
int data[] = new int[arraySize];
Random rnd = new Random(0);
for (int c = 0; c < arraySize; ++c)
data[c] = rnd.nextInt() % 256;
// With this, the next loop runs faster
Arrays.sort(data);
// Test
long start = System.nanoTime();
long sum = 0;
for (int i = 0; i < 100000; ++i) {
// Primary loop
for (int c = 0; c < arraySize; ++c) {
if (data[c] >= 128)
sum += data[c];
}
}
System.out.println((System.nanoTime() - start) / 1000000000.0);
System.out.println("sum: " + sum);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment