考虑以下代码:
public class Playground {
private static final int MAX = 100_000_000;
public static void main(String... args) {
execute(() -> {});
execute(() -> {});
execute(() -> {});
execute(() -> {});
}
public static void execute(Runnable task) {
Stopwatch stopwatch = Stopwatch.createStarted();
for (int i = 0; i < MAX; i++) {
task.run();
}
System.out.println(stopwatch);
}
}
Run Code Online (Sandbox Code Playgroud)
目前,我在 Temurin 17 上的 Intel MBP 上打印以下内容:
3.675 ms
1.948 ms
216.9 ms
243.3 ms
Run Code Online (Sandbox Code Playgroud)
请注意,第三次(以及任何后续)执行时速度减慢了 100*。现在,显然,这不是用Java 编写基准测试的方法。循环代码不执行任何操作,因此我希望它能够消除所有重复。另外,我无法使用 JMH 重复这种效果,这告诉我原因很棘手且脆弱。
那么,为什么会发生这种情况呢?为什么会突然出现如此灾难性的减速,幕后到底发生了什么?一个假设是 …
编辑:
我尝试在网络上搜索此行为,但到目前为止没有任何结果,问题如下:
当使用以下代码时:
Random r2 = new Random(1);
for(int p = 0; p < 25; p++) {
r2 = new Random(p);
System.out.println();
for(int i = 0; i < 15; i++)
System.out.print(Math.round(r2.nextFloat()*100) + " ");
}
Run Code Online (Sandbox Code Playgroud)
这总是会返回:
73 83 24 61 64 31 55 12 60 78 33 25 39 61 98
73 10 41 41 21 4 33 66 97 71 1 15 96 16 94
73 29 90 0 50 85 99 3 86 92 99 45 23 52 …Run Code Online (Sandbox Code Playgroud)