Page 1 of 1

define vs function for optimization

PostPosted: 04 Oct 2010, 01:11
by netiad
I have a rather simple question related to my Move Generation and wanted to know where you guys are drawing the line with your #defines. I know in chess engines speed is preferred over readability. I used defines for my north, south, .... moves. Now that I'm getting into more of the moves the readability / good code practice side of me is fighting with the optimized side. And I'm wondering what you guys are doing related to this topic.

MoveGeneration.h :
extern BitBoard getWhitePawnPushTargets(BitBoard whitePawns, BitBoard emptySquares);

MoveGeneration.c
BitBoard getWhitePawnPushTargets(BitBoard whitePawns, BitBoard emptySquares) {
return NORTH_ONE(whitePawns) & emptySquares;
}

or

MoveGeneration.h
#define GET_WHITE_PAWN_PUSH_TARGETS(whitePawns, emptySquares) (NORTH_ONE(whitePawns) & emptySquares)

Re: define vs function for optimization

PostPosted: 04 Oct 2010, 07:21
by Ron Murawski
netiad wrote:I have a rather simple question related to my Move Generation and wanted to know where you guys are drawing the line with your #defines. I know in chess engines speed is preferred over readability. I used defines for my north, south, .... moves. Now that I'm getting into more of the moves the readability / good code practice side of me is fighting with the optimized side. And I'm wondering what you guys are doing related to this topic.

MoveGeneration.h :
extern BitBoard getWhitePawnPushTargets(BitBoard whitePawns, BitBoard emptySquares);

MoveGeneration.c
BitBoard getWhitePawnPushTargets(BitBoard whitePawns, BitBoard emptySquares) {
return NORTH_ONE(whitePawns) & emptySquares;
}

or

MoveGeneration.h
#define GET_WHITE_PAWN_PUSH_TARGETS(whitePawns, emptySquares) (NORTH_ONE(whitePawns) & emptySquares)



I prefer using functions, but I make them inline functions so, in debug mode, the parameters can be type-checked. I don't believe there's any difference in speed of #define vs inline function as long as the compiler is instructed to maximize optimizations.

Ron

Re: define vs function for optimization

PostPosted: 04 Oct 2010, 20:49
by Dann Corbit
Macros have other nasty behavior.
For instance:
#define SQUARE(x) ((x) * (x))
seems sensible enough.
However:
dp1sq = SQUARE(d++);
introduces undefined behavior.
With a function call, there is a sequence point. Even with inline functions, it must perform as-if it were a function call so there is no undefined behavior.