osg*_*sgx 1 c++ optimization templates nested-loops
我可以使用模板创建一些函数的几个实例,只在一些常量参数中有所不同吗?此参数的替代数量是固定的.例如
我想不要改写(上面是1..32,两个幂)
funct(param, int upper)
{
some_loops(..)
some_heavy_code_fast_for_const_and_slow_for_variable(upper)
}
Run Code Online (Sandbox Code Playgroud)
成一套
funct_with_upper_is_1(param) // upper =1
{ manually_copied_code...heavy(1) }
funct_with_upper_is_2(param) // upper =2
{ manually_copied_code...heavy(2) }
funct_with_upper_is_4(param) // upper =4
{ manually_copied_code...heavy(4) }
funct_with_upper_is_8(param) // upper =8
{ manually_copied_code...heavy(8) }
Run Code Online (Sandbox Code Playgroud)
但进入模板化
template<int upper>
funct_with_fixed_upper(param)
{ the_original_code....heavy(upper) }
Run Code Online (Sandbox Code Playgroud)
然后
template<upper=1> funct_with_fixed_upper(param);
template<upper=2> funct_with_fixed_upper(param);
template<upper=4> funct_with_fixed_upper(param);
template<upper=8> funct_with_fixed_upper(param);
Run Code Online (Sandbox Code Playgroud)
这可能与C++ tempaltes有关吗?
==详细模式开启==
我有很多C++文件,代码类似
function_typical(long long double ***A, long long double ***B, int const_1, int const_2)
// the type "long long double" here is very correct, this is extension of compiler
{
for(int i=1;i<100000-1;i++)
for(int j=1;j<100000-1;j++)
for(int k=0;k<const_1;k++)
for(int l=k;l<const_2;l++) {
// some cray work with array like
A[i][j][l-k]+=(B[i][j][l-k]+A[i+1][j][l-k]+A[i][j+1][l-k]-A[i-1][j][k]-A[i][j-1][l-k]/2.2)/88.3;
if(A[i][j][l-k]>sin_lld(A[i][j-1][l-k])){B[i][j][l-k]=A[i][j][k]*4;}
}
}
Run Code Online (Sandbox Code Playgroud)
这只是一个例子,但是:
function_typical
并且它们的集合是固定的,例如const_1和const_2是一对:(2,3),(4,5) ,(3,5).允许对的总数小于10.这段代码的问题是它的速度非常低.如果我将此代码中的const_1和const_2修复为数字常量,编译器将在优化方面做得很好(例如,展开所有k和所有l次迭代,做一些聪明的工作).
但我实际上无法改变每组(const_1和const_2)对的每个典型函数.此外,编译器的常量传播器不能传播set info的常量函数(这是一个网络服务器,客户端选择一些const_1和const_2对形式固定集).
所以我在编译时知道对的所有替代方案.但是我没有机会手动重写每个功能.
==详细模式关闭==
提前致谢
当然,这完全有可能.如果通过模板获取int,则只要常量表达式有效,它就是有效的.
template<int const_1, int const_2> function_typical(long long double ***A, long long double ***B)
// the type "long long double" here is very correct, this is extension of compiler
{
for(int i=1;i<100000-1;i++)
for(int j=1;j<100000-1;j++)
for(int k=0;k<const_1;k++)
for(int l=k;l<const_2;l++) {
// some cray work with array like
A[i][j][l-k]+=(B[i][j][l-k]+A[i+1][j][l-k]+A[i][j+1][l-k]-A[i-1][j][k]-A[i][j-1][l-k]/2.2)/88.3;
if(A[i][j][l-k]>sin_lld(A[i][j][l-k])){B[i][j][l-k]=A[i][j][k]*4;}
}
}
Run Code Online (Sandbox Code Playgroud)
这应该直接重新编译,但你必须改变呼叫站点.另外,不要忘记模板化代码必须在所有翻译单元中具有完整的源,并且不能仅在一个中定义.