Any*_*orn 2 c c++ compiler-construction optimization
我有C/C++代码,看起来像这样:
static int function(double *I) {
int n = 0;
// more instructions, loops,
for (int i; ...; ++i)
n += fabs(I[i] > tolerance);
return n;
}
function(I); // return value is not used.
Run Code Online (Sandbox Code Playgroud)
编译器内联函数,但它没有优化n操作.我希望编译器能够识别该值从不用作rhs.是否有一些副作用,这会妨碍优化?
编译器似乎并不重要,我试过Intel和gcc.积极优化, -O3
谢谢
更完整的代码(完整代码是重复这样的块):
280 // function registers
281 double q0 = 0.0;
282 double q1 = 0.0;
283 double q2 = 0.0;
284
285 #if defined (__INTEL_COMPILER)
286 #pragma vector aligned
287 #endif // alignment attribute
288 for (int a = 0; a < int(N); ++a) {
289 q0 += Ix(a,1,0)*Iy(a,0,0)*Iz(a,0,0);
290 q1 += Ix(a,0,0)*Iy(a,1,0)*Iz(a,0,0);
291 q2 += Ix(a,0,0)*Iy(a,0,0)*Iz(a,1,0);
292 }
293 #endif // not SSE
294
295 //contraction coefficients
296 qK0 += q0*C[k+0];
297 qK1 += q1*C[k+0];
298 qK2 += q2*C[k+0];
299
300 Ix += 3*dim2d;
301 Iy += 3*dim2d;
302 Iz += 3*dim2d;
303
304 }
305 Ix = Ix - 3*dim2d*K;
306 Iy = Iy - 3*dim2d*K;
307 Iz = Iz - 3*dim2d*K;
308
309 // normalization, scaling, and storage
310 if(normalize) {
311 I[0] = scale*NORMALIZE[1]*NORMALIZE[0]*(qK0 + I[0]);
312 num += (fabs(I[0]) >= tol);
313 I[1] = scale*NORMALIZE[2]*NORMALIZE[0]*(qK1 + I[1]);
314 num += (fabs(I[1]) >= tol);
315 I[2] = scale*NORMALIZE[3]*NORMALIZE[0]*(qK2 + I[2]);
316 num += (fabs(I[2]) >= tol);
317 }
318 else {
319 I[0] = scale*(qK0 + I[0]);
320 num += (fabs(I[0]) >= tol);
321 I[1] = scale*(qK1 + I[1]);
322 num += (fabs(I[1]) >= tol);
323 I[2] = scale*(qK2 + I[2]);
324 num += (fabs(I[2]) >= tol);
325 }
326
327
328 return num;
Run Code Online (Sandbox Code Playgroud)
我唯一的猜测是潜在的浮点异常,它引入了副作用
代码确实使用n,首先将它初始化为0,然后在函数左侧的循环内部使用可能的副作用(fabs).
是否实际使用函数的返回是无关紧要的,n本身就是使用的.
更新:我在MSVC10中尝试了这个代码,它优化了整个功能.给我一个我可以尝试的完整例子.
#include <iostream>
#include <math.h>
const int tolerance=10;
static int function(double *I) {
int n = 0;
// more instructions, loops,
for (int i=0; i<5; ++i)
n += fabs((double)(I[i] > tolerance));
return n;
}
int main()
{
double I[]={1,2,3,4,5};
function(I); // return value is not use
}
Run Code Online (Sandbox Code Playgroud)