Loop parallelization
Estimate π using integral. Parallelization performed by work distribution (loop parallelization).
import org.pcj.NodesDescription;
import org.pcj.PCJ;
import org.pcj.StartPoint;
import org.pcj.Storage;
import org.pcj.PcjFuture;
import org.pcj.RegisterStorage;
@RegisterStorage(PcjExamplePiI.Shared.class)
public class PcjExamplePiI implements StartPoint {
private double f(final double x) {
return (4.0 / (1.0 + x * x));
}
@Storage(PcjExamplePiI.class)
enum Shared {
sum
}
double sum;
@Override
public void main() {
PCJ.barrier();
double time = System.nanoTime();
long nAll = 1_280_000_000;
double w = 1.0 / (double) nAll;
sum = 0.0;
// Calculate partial results with the cyclic distribution
for (int i = PCJ.myId(); i < nAll; i += PCJ.threadCount()) {
sum = sum + f(((double) i + 0.5) * w);
}
sum = sum * w;
// Wait for all tasksk to finish
PCJ.barrier();
// Gather results
PcjFuture cL[] = new PcjFuture[PCJ.threadCount()];
double pi = sum;
if (PCJ.myId() == 0) {
for (int p = 1; p < PCJ.threadCount(); p++) {
cL[p] = PCJ.asyncGet(p, Shared.sum);
}
for (int p = 1; p < PCJ.threadCount(); p++) {
pi = pi + cL[p].get();
}
}
PCJ.barrier();
// Print results
time = System.nanoTime() - time;
if (PCJ.myId() == 0) {
System.out.format(" %.7f %.7f time %.5f \n", pi, time * 1.0E-9, time);
}
}
public static void main(String[] args) throws IOException {
String nodesFile = "nodes.txt";
PCJ.executionBuilder (PcjExample.class)
.addNodes(new File("nodes.txt"))
.start();
}
}
Last updated