Java分支预测器测试程序有奇数结果

Java分支预测器测试程序有奇数结果,java,branch-prediction,Java,Branch Prediction,我今天读了这个问题,并试图用Java复制结果 这是我的密码: public class BranchPredictorTest { static int[] getBranchCounts1(List<Integer> list) { long t0 = System.currentTimeMillis(); int[] counts = new int[3]; for(Integer v : list)

我今天读了这个问题,并试图用Java复制结果

这是我的密码:

public class BranchPredictorTest {
    static int[] getBranchCounts1(List<Integer> list) {
        long t0 = System.currentTimeMillis();
        int[] counts = new int[3];
        for(Integer v : list)
            if(v < 1000)
                counts[0]++;
            else if(v < 2000)
                counts[1]++;
            else 
                counts[2]++;
        System.out.println("[time cost]\t" + (System.currentTimeMillis() - t0) + " ms");
        return counts;
    }

    static int[] getBranchCounts2(List<Integer> list) {
        long t0 = System.currentTimeMillis();
        int[] counts = new int[3];
        for(Integer v : list)
            counts[v/1000]++;
        System.out.println("[time cost]\t" + (System.currentTimeMillis() - t0) + " ms");
        return counts;
    }

    static void test(List<Integer> list) {
        int[] bc1 = getBranchCounts1(list);
        System.out.println(String.format("%d, %d, %d", bc1[0], bc1[1], bc1[2]));

        int[] bc2 = getBranchCounts2(list);
        System.out.println(String.format("%d, %d, %d", bc2[0], bc2[1], bc2[2]));
    }

    public static void main(String[] args) {
        Random rand = new Random();
        List<Integer> list = new ArrayList<Integer>();
        for(int i=0; i<2e7; i++) {
            list.add(rand.nextInt(3000));
        }
        test(list);
        Collections.sort(list);
        test(list);
    }
}
排序后的分支时间开销大于未排序的分支时间开销,对arraylist排序后,未分支计数的时间开销大大增加了其运行时间

编辑: 我在C++中尝试了同样的逻辑,结果基本符合预期:

[time cost] 248 ms
[time cost] 142 ms
[time cost] 87 ms
[time cost] 143 ms
我希望任何人都能向我解释这是如何发生的,谢谢你查看/回答我的问题。

我想你看到的(奇怪的)结果是因为你在运行它们时没有预热JVM


试着在1000多个周期的循环中运行上述内容,然后查看95%左右的百分比。

微基准标记很难。你和JMH试过这个吗?
[time cost] 248 ms
[time cost] 142 ms
[time cost] 87 ms
[time cost] 143 ms