JMH问题-测量不正确

时间:2019-12-22 20:12:53

标签: java jmh

这是我的代码:

public class JmhBenchmark {
@Param({"8", "16", "32"})

@State(Scope.Thread)
public static class st {

    public static Board br;
    public static int rowStart;
    public static int colStart;
}

@Setup(Level.Trial)
public void generateBoard() {
    st.br = new Board(boardSideSize);
    st.rowStart = 2 + (int) (Math.random() * (st.br.sideSize()));
    st.colStart = 2 + (int) (Math.random() * (st.br.sideSize()));
    st.br.insert(st.rowStart, st.colStart, 1); // first traveled node
}

@Benchmark 
public void generateTour(Blackhole bh) {
    bh.consume(Tour.solve(st.rowStart, st.colStart, 2, st.br));

}

public static void executeTest() {
    new JmhBenchmark().startBenchmark();

}

public void startBenchmark() {

    try {
        Options opt = new OptionsBuilder()
                .include(JmhBenchmark.class.getSimpleName())
                .forks(1)
                .build();
        new Runner(opt).run();
        Thread.currentThread().interrupt();

    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

public static void main(String[] args) {
    executeTest();
}

public class Tour{

public static int sideSize;
public static Board br;
public static int rowStart;
public static int colStart;
public static List<Tuple<Integer, Integer>> coord = new ArrayList<>();

static boolean solve(int row, int column, int count, Board br) {
    if (count > br.totalSize()) {
        return true;
    }

    List<int[]> nbrs = br.neighborsList(row, column);

    if (nbrs.isEmpty() && count != br.totalSize()) {
        return false;
    }

    Collections.sort(nbrs, new Comparator<int[]>() {
        public int compare(int[] x, int[] y) {
            return x[2] - y[2];
        }
    });

    for (int[] n : nbrs) {
        row = n[0];
        column = n[1];
        br.insert(row, column, count);
        coord.add(new Tuple(row - 2, column - 2));
        if (!br.orphanDet(count, row, column)
                && solve(row, column, count + 1, br)) {
            return true;
        }
        br.insert(row, column, 0);
    }

    return false;
}
}

我有solve(rowStart, colStart, 2, br)功能,可以解决骑士旅行的问题。问题如下: 您有一个(n x n)棋盘,空着,但在某个广场上只有一个骑士。您的任务是发出一系列合法的骑士动作,以使骑士恰好一次访问棋盘上的每个方块。 因此,我要根据板子尺寸(n x n)测试求解功能。可能的n值为8、16和32。问题是JMH测量的结果不合适。例如:

(boardSideSize)  Mode  Cnt  Score   Error  Units
             8  avgt    5  0,021 ± 0,001  us/op
            16  avgt    5  0,021 ± 0,001  us/op
            32  avgt    5  0,053 ± 0,004  us/op

当板子的侧面尺寸(n)为8或16时,测量值相等。我不知道我做错了什么。

同样,我尝试了这个示例,但它不起作用:

(boardSideSize)  Mode  Cnt  Score   Error  Units
            64  avgt    5  0,051 ± 0,006  us/op
             8  avgt    5  0,026 ± 0,001  us/op
            16  avgt    5  0,022 ± 0,001  us/op
            32  avgt    5  0,053 ± 0,005  us/op

经过以下测试: Java JDK 8和JMH 1.22

0 个答案:

没有答案