我有一个计算总和的函数,并根据总和的结果执行某些任务或给出警告消息。我需要在粒子轨迹模拟中运行此功能数百万次(它计算时间和位置相关的力),并注意到我的代码非常慢。
这是我的MWE:
#include <stdio.h>
#include <math.h>
int foo()
{
double sum =0;
double dummy_sum = 0;
for (size_t i=0; i<40; i++)
{
sum+=1e-2;
dummy_sum += 1e-2;
}
if (sum>5.) // normally this should not happen
{
printf("warning message!\n");
return(-1);
}
else if(sum >0)
{
// normal behavior
}
return(0);
}
int main()
{
int fooint;
for(size_t i=0; i<5e9; i++)
{
fooint = foo();
if(fooint!=0)
{
return(fooint);
}
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我gcc -Ofast -std=c99 test.c -o test.exe使用gcc版本4.8.5进行编译。
为了找到一种优化我的功能的方法,我运行了 …