我完全无法言语,我不知道发生了什么......
//import java.util.Random;
public class TestInProgress {
public static void main(String[] args) {
long start, end;
long average;
// Random random= new Random();
for(int j=0; j<5; j++) {
average= 0L;
for(int i=0; i<100; i++) {
start= System.nanoTime();
double temp= fastComputeSigm(0.0);
end= System.nanoTime();
average+= (end - start);
}
average= average/ 100L;
System.out.println("AVERAGE FASTCOMPUTE: "+average);
average= 0L;
for(int i=0; i<100; i++) {
start= System.nanoTime();
double temp= Math.exp(0.0)/(1.0 + Math.exp(0.0));
end= System.nanoTime();
average+= (end - start);
}
average= average / 100L;
System.out.println("AVERAGE SIGMOID: "+average);
}
}
static double fastComputeSigm(double value) {
return 0.0;
}
}
最令人惊讶的是输出:
AVERAGE FASTCOMPUTE: 98 AVERAGE SIGMOID: 38625 AVERAGE FASTCOMPUTE: 106 AVERAGE SIGMOID: 65 AVERAGE FASTCOMPUTE: 299 AVERAGE SIGMOID: 201 AVERAGE FASTCOMPUTE: 36 AVERAGE SIGMOID: 65 AVERAGE FASTCOMPUTE: 53 AVERAGE SIGMOID: 57
看到了吗?我取消注释 Random (及其导入) 你会期待什么?输出:
AVERAGE FASTCOMPUTE: 90 AVERAGE SIGMOID: 324 AVERAGE FASTCOMPUTE: 131 AVERAGE SIGMOID: 73 AVERAGE FASTCOMPUTE: 217 AVERAGE SIGMOID: 36 AVERAGE FASTCOMPUTE: 53 AVERAGE SIGMOID: 12 AVERAGE FASTCOMPUTE: 53 AVERAGE SIGMOID: 69
我在 eclipse Oxygen.3a 版本 (4.7.3a) 上尝试过这个 我正在使用java 10.0.2 我的电脑配备 Intel Core i5-7300HQ 具有这些高速缓存存储器:L1 256、L2 1024、L3 6M 我在 Windows 10 上运行
注意:我尝试使用 j<1,2,3,... 多次进行 forloop 没有帮助第一个 sigmoid 总是有荒谬的时间长度
编辑:尝试使用 Windows 命令行(javac 和 java)启动它,结果相同
最佳答案
一般来说,指出微基准测试的棘手之处的评论是正确的,您应该使用 JMH。在这种特殊情况下,您的计时/基准测试代码似乎引入了本来就不存在的延迟。
这是代码的压缩版本,它演示了该问题不是由使用 Random
触发的,而是由使用 System.nanoTime()
(其中Random()
内部调用)
public static void main(String[] args) {
long start, end, average;
double temp = 0;
// start = System.nanoTime();
average = 0L;
for (int i = 0; i < 100; i++) {
start = System.nanoTime();
temp += Math.exp(0.0) / (1.0 + Math.exp(0.0));
end = System.nanoTime();
average += (end - start);
// System.out.println(i + " " + (end - start));
}
System.out.println("AVERAGE: " + (average / 100));
System.out.println("temp: " + temp);
}
当我取消注释 start = System.nanoTime()
时,我观察到了 100 倍的加速 - 此时,重要的是要记住这里的单位是纳秒
,所以我们对于运行时在后台执行的操作非常敏感。如果取消注释 System.out.println(i + ""+ (end - start));
,您会看到偶尔出现的打嗝,这是导致整个速度变慢的原因。虽然追查这个问题的原因可能很有趣,但以下版本的代码表明这是由于测量而不是核心功能造成的,因此您可能需要确保这是您想要的想把自己的时间花在 [1] 上:
public static void main(String[] args) {
double temp = 0;
long start = System.nanoTime();
for (int i = 0; i < 100; i++) {
temp += Math.exp(0.0) / (1.0 + Math.exp(0.0));
}
System.out.println("AVERAGE: " + ((System.nanoTime() - start) / 100));
System.out.println("temp: " + temp);
}
此处的 AVERAGE 值与之前的版本类似,但未注释 start = System.nanoTime()
。
[1] 如果您有兴趣深入研究这一特定行为,请尝试在使用禁用编译器的 -Xint
VM 选项运行时对测试进行计时。
关于java.util.Random 使计算速度提高 100 倍?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53133961/