Dynamic -ffast-math

天涯浪子 提交于 2020-01-13 09:48:07

问题


Is it possible to selectively turn -ffast-math on/off during runtime? For example, creating classes FastMath and AccurateMath with the common base class Math, so that one would be able to use both implementations during runtime? Ditto for flashing subnormals to zero, etc.

In particular, I don't know whether compiling with -ffast-math would emit an instruction that would, once executed, affect all numerical computations in the thread (for example, setting a flag to flush subnormals to zero).


回答1:


Try this:

gcc -ffast-math -c first.c
gcc -c second.c
gcc -o dyn_fast_math first.o second.o

Putting uniquely-named functions in first.c and second.c. This should do the trick. There is rarely any "global" impact of a compiler optimization. If one does exist, linking will likely fail due to the conflict.

I tried a small sample without problem.

Here's an example.

first.c

extern double second();

double  first ()
{
    double  dbl;

    dbl = 1.0;
    dbl /= 10.0;

    return  dbl;
}

int main ()
{
    printf("first = %f\n", first());
    printf("second = %f\n", second());

    return  0;
}

second.c

double  second ()
{
    double  ddbl;

    ddbl = 1.0;
    ddbl /= 10.0;

    return  ddbl;
}

compilation

gcc -S first.c
gcc -c first.s
gcc -ffast-math -S second.c
gcc -ffast-math -c second.s
gcc -o prog first.o second.o

Check the difference between first.s and second.s and you'll find this:

movapd  %xmm1, %xmm2
divsd   %xmm0, %xmm2
movapd  %xmm2, %xmm0

changes to this:

mulsd   %xmm1, %xmm0

Both functions are called, and both return the expected result.




回答2:


If you don't want to muck with the build system, you can do the following:

#pragma fast-math push
#pragma fast-math on
[..]
#pragma fast-math pop

GCC may have a slightly different syntax, but I would expect it's possible too.



来源:https://stackoverflow.com/questions/18197344/dynamic-ffast-math

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!