I'm writing a chess engine in C# with magic bitboards and it's very slow right now. It takes 2 minutes to calculate perft 6 (119,060,324 positions) from the initial position when other engines can do it in 1-3 seconds. I'm currently using this method to find the indices of all 1s in the bitboard:
public static readonly int[] index64 = {
0, 47, 1, 56, 48, 27, 2, 60,
57, 49, 41, 37, 28, 16, 3, 61,
54, 58, 35, 52, 50, 42, 21, 44,
38, 32, 29, 23, 17, 11, 4, 62,
46, 55, 26, 59, 40, 36, 15, 53,
34, 51, 20, 43, 31, 22, 10, 45,
25, 39, 14, 33, 19, 30, 9, 24,
13, 18, 8, 12, 7, 6, 5, 63
};
public static List<int> bitScan(ulong bitboard) {
var indices = new List<int>(30);
const ulong deBruijn64 = 0x03f79d71b4cb0a89UL;
while (bitboard != 0) {
indices.Add(index64[((bitboard ^ (bitboard - 1)) * deBruijn64) >> 58]);
bitboard &= bitboard - 1;
}
return indices;
}
This is the method that is called the most, and I want to speed it up. Is there a faster way to do this? I want to return an array instead of a list, but I can't figure out how since the number of bits is unknown (and I don't want empty elements since I have lots of foreach loops).
Any advice is appreciated.