package edu.rice.hj.example.comp322.labs.lab2; import edu.rice.hj.api.HjMetrics; import edu.rice.hj.api.SuspendableException; import edu.rice.hj.runtime.config.HjSystemProperty; import edu.rice.hj.runtime.metrics.AbstractMetricsManager; import static edu.rice.hj.Module1.*; /** * ArraySum1.hj --- Parallel iterative example program for computing the sum of an array *

* This example program creates an array of n random int's, and computes their sum in parallel. The default value of n * is 8, but any array size can be provided as argv[0] by going into the run configuration and putting it in the program * arguments field on intelliJ, or by typing java ArraySumRecursive n on the command line *

* To obtain abstract performance metrics, select the appropriate compiler option. *

* NOTE: this example program is for illustrative purposes, and is not intended to be used as a performance benchmark. * * @author Vivek Sarkar (vsarkar@rice.edu) */ public class ArraySumRecursive { /** * Main method, runs the ArraySum * * @param args - the input parameters */ public static void main(final String[] args) { // Setup metrics HjSystemProperty.abstractMetrics.set(true); launchHabaneroApp(() -> { final String strategyStr = System.getProperty("arraysum.work.strategy"); System.out.println("Strategy: " + strategyStr); final int n = ArraySumUtil.readLengthArgument(args); final int[] X = ArraySumUtil.initialize(n); final int expectedResult = ArraySumUtil.expectedResult(X); computeSumReduction(X, 0, n); // Output System.out.println("Sum of " + n + " elements = " + X[0] + " (should be " + expectedResult + ")"); }, () -> { // Print out the metrics data final HjMetrics actualMetrics = abstractMetrics(); AbstractMetricsManager.dumpStatistics(actualMetrics); }); } /** * Method that computes the sum of the elements in an array between two indices, a start index and an end index. * Mutates the array that is given as input, final result of the sum is stored in at the index listed as the start * index * * @param x - the array to sum (is mutated) * @param startIndex - the leftmost index to be considered in the sum of the array. Is also where the result will be * stored * @param endIndex -the rightmost index to be considered in the sum of the array. */ protected static void computeSumReduction(final int[] x, final int startIndex, final int endIndex) throws SuspendableException { if (endIndex - startIndex <= 1) { // nothing to do return; } // Parallel reduction final int midIndex = (startIndex + endIndex) / 2; finish(() -> { async(() -> { computeSumReduction(x, startIndex, midIndex); }); computeSumReduction(x, midIndex, endIndex); }); x[startIndex] = ArraySumUtil.doOperation(x, startIndex, midIndex); } }