Help on optimizing

Discussion of chess software programming and technical issues.

Moderators: hgm, Rebel, chrisw

ericlangedijk

Help on optimizing

Post by ericlangedijk »

First I'm going to try and optimize the movegenerator which takes most of the time.
It's in delphi and written for win32.
Is this a reasonably fast way to do the BSF?

Code: Select all

function BSF(var Bitboard: TBitboard; var Q: Byte): Boolean;
// eax --> BitBoard
// edx --> Q
// result --> eax
asm
  bsf ecx, [eax]
  jz @scanhi
  btc [eax], ecx
  jmp @found
  @scanhi:
  bsf ecx, [eax+4]
  jz @notfound
  btc [eax+4], ecx
  add ecx, 32
  @found:
    mov [Q], cl        // assign Q = mov[edx], cl
    mov al, 1          // return true
    jmp @exit          // ret
  @notfound:
    xor al, al         // return false
  @Exit:
end;


  PieceBitBoard := PieceBitBoards[WhiteBishop];
  while BSF(PieceBitBoard, Q) do
  begin
    MoveBitBoard := GetBishopAttacks(Q) and not ColorBitBoards[cWhite];
    while BSF(MoveBitBoard, T) do
      aMoves.Add(WhiteBishop, Q, T, BoardArray[T]);
  end;
Gerd Isenberg
Posts: 2250
Joined: Wed Mar 08, 2006 8:47 pm
Location: Hattingen, Germany

Re: Help on optimizing

Post by Gerd Isenberg »

ericlangedijk wrote:First I'm going to try and optimize the movegenerator which takes most of the time.
It's in delphi and written for win32.
Is this a reasonably fast way to do the BSF?
On most (all?) x86 processors btc via indirect memory operand might be a bottleneck, since it is able to work on vectors with indices far greater 31, it has (much) worse latency even for indices <= 31. May be better to spend an extra register for the bsf-btc pair. I suggest to use a precondition and bsf without reset and notfound always called with none empty bitboards, otherwise likely the same condition is asked twice, inside and outside BSF. Instead of btc or btr, X "and" (X-1) might be faster (but does not work for bsr instead of bsf).

Code: Select all

function bsf&#40;var Bitboard&#58; TBitboard&#41;&#58; Integer;
// eax --> BitBoard
// result --> eax
asm
  bsf ecx, &#91;eax&#93;
  jnz @found
  @scanhi&#58;
  bsf ecx, &#91;eax+4&#93;
  add ecx, 32
  @found&#58;
    mov eax, ecx
  @Exit&#58;
end; 


  PieceBitBoard &#58;= PieceBitBoards&#91;WhiteBishop&#93;;
  while ( PieceBitBoard != 0 ) do
  begin
    Q &#58;= bsf ( PieceBitBoard );
    MoveBitBoard &#58;= GetBishopAttacks&#40;Q&#41; and not ColorBitBoards&#91;cWhite&#93;;
    while ( MoveBitBoard != 0 ) do
    begin
      T &#58;= bsf ( MoveBitBoard );
      aMoves.Add&#40;WhiteBishop, Q, T, BoardArray&#91;T&#93;);
      MoveBitBoard &#58;= MoveBitBoard and &#40;MoveBitBoard - 1&#41;;
    end;
    PieceBitBoard &#58;= PieceBitBoard and &#40;PieceBitBoard - 1&#41;;
  end;