Is it bad to use compiler-specific functions in your source? i.e Should I avoid using them?
The answer is "it depends." A naive hand-rolled popcount
function requires but a few lines of code that are easy to understand, easy to test, and highly portable.
Suppose on performance testing you find that the CPU spends a tiny, tiny fraction of the execution time in this nice simple chunk of code. In this case, there is no reason to pollute your code with #ifdef this
, #elif defined that
, and #elif defined something_else
. Optimized code oftentimes is rather ugly code, with #ifdef
being about as ugly as it gets.
On the other hand, suppose on performance testing you find that the CPU spends a significant fraction of the execution time in this nice simple chunk of code, and suppose you find that the compiler-specific intrinsics reduce this by a significant amount. This can justify getting ugly, but keep in mind that that ugly code may be fragile. Your code is now at the mercy of vendors maintaining backward compatibility with their intrinsics. There is no guarantee that that will continue.
One final note: In the future you might well find that your naive hand-rolled popcount
function suddenly becomes just as fast as the compiler-specific ugliness. Compiler writers (and hence compilers) have become ever more adept at recognizing the intent of code. A compiler might well recognize that your small number of lines of code does exactly what __popcount_using_specialized_assembly_instructions
does, and thereby compiles your code to call that specialized function. You could have done the same using a bunch of macro commands. But what happens when the authors of the library change the name of the function? The compiler will be cognizant of that change and compile your naive hand-rolled popcount
function to call the renamed function. Your macro plagued code will not.