相同的 for 循环 为什么 Java 比 c 的速度快?

151 天前
 chaoschick
Java

public class DuffDevice {

private static int duff2(int count) {
int i = 0;
do {
++i;
} while (--count >0);
return i;
}

public static void main(String[] args) {
int duff;
long start, end;
DuffDevice duffDevice = new DuffDevice();

start = System.currentTimeMillis();
duff = duff2(Integer.MAX_VALUE - 7);
end = System.currentTimeMillis();
System.out.println(duff + " " + (end - start) + " ms");
}
}

C
#include <sys/time.h>
#include <stdio.h>

int duff(int count) {
}

int main(int argc, char* argv[]) {
struct timeval start_time, end_time;

gettimeofday(&start_time, NULL);

long count = 2147483640;
long i = 0;

do {
++i;
} while (--count);

gettimeofday(&end_time, NULL);

int total_time = 1000000 * (end_time.tv_sec - start_time.tv_sec) + (end_time.tv_usec - start_time.tv_usec);
printf("%d us", total_time);
printf("\n");
printf("%.3f ms", (double) total_time / 1000);
printf("\n");

printf("%l", i);
return 0;
}

Java 耗时情况
2 ms

C 耗时情况
4638.628 ms

性能怎么会相差这么大?
3678 次点击
所在节点    程序员
23 条回复
PTLin
151 天前
这种代码不长的,而且是循环引起的性能问题,建议直接看汇编/字节码,来确定问题以及验证猜想。
或者用完整的性能测试框架测试,避免出现一个优化后测试的,一个还是调试模式测试的的这种低级问题。
debuggerx
151 天前
[为什么下面程序递归计算斐波那契数列 java 比 c++要快 - RednaxelaFX 的回答]( https://www.zhihu.com/question/56683164/answer/150190561)
LiaoMatt
150 天前
C 代码的变量用 register 修饰会不会更快

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1003556

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX