【发布时间】:2014-09-15 21:24:17
【问题描述】:
我正在学习算法和算法分析课程。我想知道一个简单的操作+,-,/,*可以在我的电脑上执行多少操作。所以我写了一个简单的秒表如下:
public class NanosecondsStopWatch implements StopWatch {
private PrintStream stream;
public NanosecondsStopWatch(PrintStream stream) {
this.stream = stream;
}
@Override
public void timeAndPrint(Action action) {
long start = System.nanoTime();
action.doAction();
long end = System.nanoTime();
stream.println(end-start);
}
}
public class TestingOperationsTime {
public static void main(String[] strings) {
StopWatch watch = new NanosecondsStopWatch(System.out);
watch.timeAndPrint(new Action() {
@Override
public void doAction() {
int i= 2*2;
}
});
watch.timeAndPrint(new Action() {
@Override
public void doAction() {
int i= 2/2;
}
});
watch.timeAndPrint(new Action() {
@Override
public void doAction() {
int i= 2-2;
}
});
watch.timeAndPrint(new Action() {
@Override
public void doAction() {
int i= 2+2;
}
});
}
}
结果如下
2529
454
355
335
但是,如果我改变操作的顺序,这样说:
public class TestingOperationsTime {
public static void main(String[] strings) {
StopWatch watch = new NanosecondsStopWatch(System.out);
watch.timeAndPrint(new Action() {
@Override
public void doAction() {
int i= 2-2;
}
});
watch.timeAndPrint(new Action() {
@Override
public void doAction() {
int i= 2*2;
}
});
watch.timeAndPrint(new Action() {
@Override
public void doAction() {
int i= 2/2;
}
});
watch.timeAndPrint(new Action() {
@Override
public void doAction() {
int i= 2+2;
}
});
}
}
结果还是差不多:
2494
332
309
326
你如何解释这种行为?
- 操作系统:Ubuntu 14.04
- Java:1.7.0_65
- OpenJDK 运行时环境 (IcedTea 2.5.1) (7u65-2.5.1-4ubuntu1~0.14.04.2)
- OpenJDK 64 位服务器 VM(内部版本 24.65-b04,混合模式)
- javac 1.7.0_67
【问题讨论】:
-
因为它们是常量表达式,所以
2*2、2/2、2-2和2+2在编译时进行评估。您的时间不反映计算时间。 -
Is there a stopwatch in java 的可能重复项
-
如果您想知道某件事需要多长时间,请多次执行该操作,然后计算平均值。
-
如果执行多次,结果会小于1ns。
标签: java