本文介绍了简单循环的速度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为了测试速度,我在 Java 中做了一个简单的循环.与 C 中的相同循环相比,它需要更多时间.执行 20 亿次迭代大约需要 6.5 秒
I have made a simple loop in Java just to test the speed. Compared to the same loop in C it takes a lot more time. 2 billion iterations takes about 6.5 seconds when its executed
如果它被认为很慢 - 可以做些什么来提高性能?
If its considered to be slow - what could one do to improve the performance?
能不能怪JVM的启动?或者 - JIT 编译器没有完成它的工作吗?
Could one blame the startup of the JVM? Or - is the JIT-compiler not doing its job?
- 平台:windows xp
处理器速度:3.4 GHz
- platform: windows xp
processor speed: 3.4 GHz
public class Jrand {
public static void main (String[] args) {
float f;
long startTime = System.currentTimeMillis();
for (int i = 0; i < 2000000000; i++) {
f = i * 0.0001F;
}
long endTime = System.currentTimeMillis();
float totalTime = (endTime - startTime);
System.out.println("time: " + totalTime/1000);
}
}
推荐答案
这个
for (int j = 0; j < 10; j++) {
float f;
long start = System.nanoTime();
for (int i = 0; i < 2000000000; i++) {
f = i * 0.0001F;
}
long end = System.nanoTime();
long timeToCallNanoTime = System.nanoTime() - end;
long time = Math.max(0, end - start - timeToCallNanoTime);
System.out.println("time: " + time + " ns.");
}
印刷品
time: 2580790 ns.
time: 4241443 ns.
time: 17 ns.
time: 0 ns.
time: 0 ns.
time: 0 ns.
time: 0 ns.
time: 0 ns.
time: 5 ns.
time: 0 ns.
如您所见,JIT 已经完全优化了循环.没有比这更快的了.
As you can see the JIT has optimised the loop away completely. It can't get faster than that.
这篇关于简单循环的速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!