简体   繁体   中英

Is it possible to remove this conditional statement?

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM