This is a very interesting problem to study. I wrote this simple code to check the optimal value of the serial threshold. I could not come to any specific conclusions, although most likely because I am running it on an old laptop with two processors. The only consistent observation after many runs was that the time spent quickly drops to a consistent threshold of 100. Try running this code and let me know what you find. Also at the bottom, I added a python script to plot the results so that we can visually see the trend.
import java.io.FileWriter; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.RecursiveAction; public class Testing { static int SEQ_THRESHOLD; public static void main(String[] args) throws Exception { int size = 100000; int[] v1 = new int[size]; int[] v2 = new int[size]; int[] v3 = new int[size]; for (int i = 0; i < size; i++) { v1[i] = i; // Arbitrary initialization v2[i] = 2 * i; // Arbitrary initialization } FileWriter fileWriter = new FileWriter("OutTime.dat"); // Increment SEQ_THRESHOLD and save time taken by the code to run in a file for (SEQ_THRESHOLD = 10; SEQ_THRESHOLD < size; SEQ_THRESHOLD += 50) { double avgTime = 0.0; int samples = 5; for (int i = 0; i < samples; i++) { long startTime = System.nanoTime(); ForkJoinPool fjp = new ForkJoinPool(); fjp.invoke(new VectorAddition(0, size, v1, v2, v3)); long endTime = System.nanoTime(); double secsTaken = (endTime - startTime) / 1.0e9; avgTime += secsTaken; } fileWriter.write(SEQ_THRESHOLD + " " + (avgTime / samples) + "\n"); } fileWriter.close(); } } class VectorAddition extends RecursiveAction { int[] v1, v2, v3; int start, end; VectorAddition(int start, int end, int[] v1, int[] v2, int[] v3) { this.start = start; this.end = end; this.v1 = v1; this.v2 = v2; this.v3 = v3; } int SEQ_THRESHOLD = Testing.SEQ_THRESHOLD; @Override protected void compute() { if (end - start < SEQ_THRESHOLD) { // Simple vector addition for (int i = start; i < end; i++) { v3[i] = v1[i] + v2[i]; } } else { int mid = (start + end) / 2; invokeAll(new VectorAddition(start, mid, v1, v2, v3), new VectorAddition(mid, end, v1, v2, v3)); } } }
and here is a Python script to build the results:
from pylab import * threshold = loadtxt("./OutTime.dat", delimiter=" ", usecols=(0,)) timeTaken = loadtxt("./OutTime.dat", delimiter=" ", usecols=(1,)) plot(threshold, timeTaken) show()
Sourabh bhat
source share