Reputation: 18877
I'm writing a solver for a simple game and when I profile my code, these lines are eating up 40% of the CPU time (via the Visual Studio profiler when run against a Release build).
unsigned int notVisited, move; // initialized outside of this code
bool pathFree = (notVisited & move) == move;
if (pathFree) successors |= move;
I suspect the actual slow down is the branch just below that line and compiling with optimizations is causing it to find the wrong line. All of this happens in a loop that runs about 10 times per function call. Is there some bit magic that can perform the above lines without the need for the branch?
Upvotes: 1
Views: 173
Reputation: 2036
The sad thing is, any answer given here will not make any practical sense to you until you compare the assembly output of your code and proposed version, on your compiler with its settings, and all the surrounding code.
Speaking just from the perspective of code brevity, I liked the comment by Pete Becker
Upvotes: 2
Reputation: 182083
This, perhaps?
successors |= (move & -((int) pathFree));
If pathFree
is false, (int) pathFree
is 0, so the entire right side is 0 and the |=
does nothing.
If pathFree
is true, (int) pathFree
is 1, which negated is -1 so all bits are 1, so the entire right side evaluates to move
.
I doubt it's faster, though. You end up doing a memory write in both cases, where previously it could be avoided if the condition was false.
Upvotes: 5