用Java编写求π包含并行和串行并且得出消耗时间
时间: 2024-03-08 17:47:18 浏览: 69
好的,我可以为您编写Java代码来求π,并使用并行和串行方法,并计算它们的执行时间。下面是代码:
```java
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
public class PiCalculator {
private static final int NUM_ITERATIONS = 1000000000;
private static class PiTask extends RecursiveTask<Double> {
private final int start;
private final int end;
public PiTask(int start, int end) {
this.start = start;
this.end = end;
}
@Override
protected Double compute() {
double sum = 0.0;
for (int i = start; i < end; i++) {
double x = (i + 0.5) / NUM_ITERATIONS;
sum += 4.0 / (1.0 + x * x);
}
return sum;
}
}
public static double calculatePiSequentially() {
double sum = 0.0;
for (int i = 0; i < NUM_ITERATIONS; i++) {
double x = (i + 0.5) / NUM_ITERATIONS;
sum += 4.0 / (1.0 + x * x);
}
return sum / NUM_ITERATIONS;
}
public static double calculatePiInParallel() {
ForkJoinPool pool = new ForkJoinPool();
double sum = pool.invoke(new PiTask(0, NUM_ITERATIONS));
pool.shutdown();
return sum / NUM_ITERATIONS;
}
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
double piSequential = calculatePiSequentially();
long endTime = System.currentTimeMillis();
System.out.println("Sequential pi = " + piSequential);
System.out.println("Sequential time = " + (endTime - startTime) + " ms");
startTime = System.currentTimeMillis();
double piParallel = calculatePiInParallel();
endTime = System.currentTimeMillis();
System.out.println("Parallel pi = " + piParallel);
System.out.println("Parallel time = " + (endTime - startTime) + " ms");
}
}
```
这个程序会计算π值,它使用了 Fork/Join 框架来实现并行计算。在 `PiTask` 中,`compute()` 方法根据给定的起始和结束位置计算一段π值的总和。在 `calculatePiSequentially()` 方法中,程序使用单个线程来计算π。在 `calculatePiInParallel()` 方法中,程序使用 Fork/Join 框架来将计算任务分配给多个线程。
您可以运行这个程序来获得计算π的时间并比较串行和并行方法的结果。
阅读全文