我有一段代码需要快速运行,我正在优化运行数百万亿次的内部循环。
为了追求这个,我一直在这个内部循环中编写几个不同版本的代码,一些使用朴素的方法,一些使用 SSE 内在函数,等等。我做这一切的想法是当我运行它时在特定的硬件组合上,我可以运行测试,查看哪种实现/编译器命令组合效果最好并运行它。
起初只有两种不同的方法时,我在循环内使用了一个简单的条件编译,如下所示
do
{
#ifdef naive_loop
//more code here
#endif
#ifdef partially_unrolled_loop
//more code here
#endif
}
while( runNumber < maxRun );
后来随着我尝试的变体和不同事物的数量增加,它变成了这样:
#ifdef naive_loop
void CalcRunner::loopFunction()
{
//code goes here
}
#endif
#ifdef partially_unrolled_loop
void CalcRunner::loopFunction()
{
//code goes here
}
#endif
#ifdef sse_intrinsics
void CalcRunner::loopFunction()
{
//code goes here
}
#endif
//etc
然而,这使我的文件变得庞大且难以阅读。 有没有更优雅的方法来做到这一点?
最佳答案
您可以使用模板和模板特化来完成这项工作。例如:
template <typename T>
class CalcRunner;
template <>
class CalcRunner<naive_loop>
{
void loopFunction(void){...}
};
template <>
class CalcRunner<partially_unrolled_loop>
{
void loopFunction(void){...}
};
// Now instantiate what you wanna at compiler time
typename CalcRunner<partially_unrolled_loop> CalcRunner_t
int main()
{
CalcRunner_t runner;
runner.loopFunction();
}
关于c++ - 如何进行条件编译 'elegantly' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22544717/