0

出于某种原因,我的方法“bishops”在从主方法调用时比从静态初始化块调用时运行得快得多。这是正常现象还是bug?

public class Magic
{
    public static void main(String[] args)
    {
        bishops();
    }

    public static void bishops()
    {
        //PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("bishops.txt")));
        BISHOP_SHIFTS = new int[64];
        BISHOP_COMBOS = new long[64][];
        for (int square = 0; square < 64; square++) {System.out.println("bbb " + square);
            int NUMBER = bitCount(BISHOP_ATTACKS[square]);
            BISHOP_SHIFTS[square] = 64 - NUMBER;
            long x = BISHOP_ATTACKS[square];
            long[] MAPS = new long[NUMBER];
            for (int n = 0; n < NUMBER; n++) {
                int i = bitScan(x);
                MAPS[n] = (1L << i);
                x -= MAPS[n];
            }
            int C = 1 << NUMBER;
            BISHOP_COMBOS[square] = new long[C];
            for (int i = 0; i < C; i++) {
                BISHOP_COMBOS[square][i] = 0;
                int j = i;
                for (int n = 0; n < NUMBER; n++) {
                    if ((j & 1) == 1)
                        BISHOP_COMBOS[square][i] |= MAPS[n];
                    j >>>= 1;
                }
                //out.println("SQUARE " + square);
                //out.println(toBitboardString(BISHOP_COMBOS[square][i]));
                //out.println();
            }
        }
        //out.close();

        bishopMagics();
    }

    public static void bishopMagics()
    {
        BISHOP_MAGICS = new long[64];
        Random r = new Random();

        for (int square = 0; square < 64; square++) {System.out.println("asdffff " + square);
            int i;
            int LENGTH = BISHOP_COMBOS[square].length;
            long magic;
            do {
                magic = r.nextLong() & r.nextLong() & r.nextLong();
                //final int COUNT = bitCount(BISHOP_MASKS[square]);
                boolean[] used = new boolean[LENGTH];
                for (int j = 0; j < used.length; j++)
                    used[j] = false;
                for (i = 0; i < LENGTH; i++) {
                    int index = (int) ((BISHOP_COMBOS[square][i] * magic) >>> BISHOP_SHIFTS[square]);
                    if (used[index])
                        break;
                    else
                        used[index] = true;
                }
            } while (i < LENGTH);
            BISHOP_MAGICS[square] = magic;
            System.out.println(magic);
        }

        //bishopTable();
    }

    /*
     * Lots of stuff omitted
     */

    static
    {
        //bishops();
    }
}
4

1 回答 1

6

随着 JVM 预热(加载类 es 并编译代码),第二次运行速度将比第一次快得多。静态块总是首先被调用。

尝试从 main() 或静态块运行它两次,看看每次需要多长时间

顺便说一句:我会将任何日志记录到控制台,因为这会大大减慢代码速度。

于 2012-06-27T15:07:14.607 回答