gpt4 book ai didi

java - 使用 JNI 可能会提高性能吗?

转载 作者:行者123 更新时间:2023-12-03 02:49:57 24 4
gpt4 key购买 nike

一两年前,我创建了一个用 Java 编写的程序来模拟 n 体问题。最近,我疯狂地想将程序重写为分布式程序,以便能够以更高的精度模拟更大的质量。

对旧程序的分析表明,正如预期的那样,程序的大约 90% 都用于计算浮点类型值。如果我没记错的话,C/C++ 在算术运算方面比 Java 快很多,尤其是浮点类型计算。

无论如何,这就是实际问题:)

通过使用 JNI,我可以预期速度的提高等于用 C/C++ 编写的程序(用于计算)还是 JVM 会减慢速度?

最佳答案

大多数浮点运算在 Java 中大约需要 1 纳秒,因此我不确定您期望它们在 C++ 中要快多少。

然而,JNI 调用通常需要大约 30 ns,因此除非每次调用执行大量浮点运算,否则成本会高于节省的成本。

正如以下微基准测试所示,一旦代码预热,每个操作都是亚纳秒。

如果您希望速度更快,您可以使用多个核心,使其速度提高 4 倍或更多。

public static void main(String[] args) throws Exception {
int length = 200000;
double[] a = fill(new double[length]);
double[] b = fill(new double[length]);
double[] c = fill(new double[length]);
double[] x = new double[length];

for (int i = 0; i < 10; i++)
testTime(length, a, b, c, x);
}

private static void testTime(int length, double[] a, double[] b, double[] c, double[] x) {
long start = System.nanoTime();
for (int i = 0; i < length; i++)
x[i] = a[i] * b[i] + c[i];
long time = System.nanoTime() - start;
System.out.printf("Average time per double operation was %.1f ns%n", time / 2.0 / length);
}

private static double[] fill(double[] doubles) {
for (int i = 0; i < doubles.length; i++)
doubles[i] = Math.random();
return doubles;
}

打印

Average time per double operation was 10.9 ns
Average time per double operation was 17.9 ns
Average time per double operation was 1.7 ns
Average time per double operation was 1.0 ns
Average time per double operation was 0.9 ns
Average time per double operation was 0.8 ns
Average time per double operation was 0.9 ns
Average time per double operation was 0.8 ns
Average time per double operation was 1.0 ns
Average time per double operation was 0.9 ns

关于java - 使用 JNI 可能会提高性能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5727552/

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