Skip to content

Instantly share code, notes, and snippets.

@wouterd
Created March 19, 2014 16:00
Show Gist options
  • Save wouterd/9644911 to your computer and use it in GitHub Desktop.
Save wouterd/9644911 to your computer and use it in GitHub Desktop.
Testing parrallel vs serial filtering in Java8
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* Created by wouter on 19-03-14.
*/
public class ParrallelTest {
public static final int SET_SIZE = 1000000;
@org.junit.Test
public void testParallelStream() throws Exception {
Random random = new Random();
System.out.println("Filtering " + SET_SIZE + " items...");
long timeForSerialFilter = testSerialFilter(random);
System.out.println("Time for Serial filter = " + timeForSerialFilter + "ms.");
long timeForParallelFilter = testParallelFilter(random);
System.out.println("Time for Parallel filter = " + timeForParallelFilter + "ms.");
}
private long testSerialFilter(final Random random) {
List<Data> data1 = new ArrayList<>(SET_SIZE);
for (int i = 0 ; i < SET_SIZE ; i++) {
data1.add(new Data(random.nextBoolean()));
}
long start = System.currentTimeMillis();
data1.stream().filter(it -> it.successful).count();
return System.currentTimeMillis() - start;
}
private long testParallelFilter(final Random random) {
final long start;List<Data> data2 = new ArrayList<>(SET_SIZE);
for (int i = 0 ; i < SET_SIZE ; i++) {
data2.add(new Data(random.nextBoolean()));
}
start = System.currentTimeMillis();
data2.parallelStream().filter(it -> it.successful).count();
return System.currentTimeMillis() - start;
}
private class Data {
final boolean successful;
private Data(final boolean successful) {
this.successful = successful;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment