gpt4 book ai didi

Java - 计算 PI - 单线程与多线程

转载 作者:搜寻专家 更新时间:2023-10-31 20:08:04 24 4
gpt4 key购买 nike

我不知道为什么,但我计算 PI 的单线程代码比多线程代码快得多。我正在使用 5 亿点和多线程 16 核。单 CPU 很好,多线程所有 16 个内核都是 100%,但速度较慢...

有什么线索吗??

单例

    public static double monteCarloMethodSequencialMethod(long points) {
long inCircle = 0;

for (long i = 0; i < points; i++) {

double x = Math.random();
double y = Math.random();

if(x * x + y * y <= 1) inCircle++;
}

return 4.0 * inCircle / points;
}

Sequencial Monte-Carlo estimated PI value : 3.141562496. Executed in 13432.927304 ms.

多线程

    public double calculatePI() throws InterruptedException, ExecutionException {

double sum = 0;

List<Future<Double>> tasks = new ArrayList<>();

ExecutorService executor = Executors.newFixedThreadPool(nProcessors);

for (long i = 0; i < points; i += points / nProcessors) {
Future<Double> task = executor.submit(() -> {
long inCircle = 0;
double val = 0;

for(long k = 0; k < points / nProcessors; k++) {
double x = Math.random();
double y = Math.random();

if(x * x + y * y <= 1) inCircle++;
}
val = 4.0 * inCircle;

return val;
});

tasks.add(task);
}

long pending = nProcessors;
while(pending != 0) {
for(Future<Double> future : tasks) {
if(future.isDone()) {
sum += future.get();
pending--;
System.out.println(pending + " task are still pending");
}
}
}

executor.shutdown();

return sum / points;
}

Concurrent Monte-Carlo estimated PI value : 3.141666048. Executed in 116236.812471 ms.

最佳答案

在您的代码中,您大量使用了随机数。请注意,java.util.Random 在这种情况下并不理想,因为它会在线程之间造成拥塞。这是一个已知的性能问题(来源 documentation):

Instances of java.util.Random are threadsafe. However, the concurrent use of the same java.util.Random instance across threads may encounter contention and consequent poor performance. Consider instead using ThreadLocalRandom in multithreaded designs.

我建议切换到 ThreadLocalRandom相反:

java.util.concurrent.ThreadLocalRandom.current().nextDouble()

关于Java - 计算 PI - 单线程与多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56676714/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com