C ++浮点常量是否总是存储在静态内存中? [英] Are C++ floating point constants always stored in static memory?

查看:51
本文介绍了C ++浮点常量是否总是存储在静态内存中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在他的书使用C ++优化软件 Agner Fog提供了以下示例:

In his book Optimizing Software in C++ Agner Fog gives the following example:

字符串常量和浮点常量存储在静态中记忆.示例:

String constants and floating point constants are stored in static memory. Example:

// Example 7.2
a = b * 3.5;
c = d + 3.5;

此处,常数3.5将存储在静态存储器中.大多数编译器会认识到两个常数是相同的,因此只有一个常量需要存储.

Here, the constant 3.5 will be stored in static memory. Most compilers will recognize that the two constants are identical so that only one constant needs to be stored.

所有浮点常量是否总是始终存储在静态存储器中?

Are all floating point constants always stored in static memory?

为什么不能将它们存储在堆栈中?说出他给出的例子.

Why can't they be stored on the stack? Say in the example he gives.

推荐答案

感谢您的示例.没错,当使用gcc为64位模式关闭优化(-O0)时,它将常量存储在代码中.如果您针对32位模式进行编译,它将常量存储在内存中.

Thank you for the example. You are right that it stores the constants in the code when compiled with gcc for 64-bit mode with optimiztion off (-O0). It stores the constants in memory if you compile for 32-bit mode.

如果启用优化(-O3),则会简单地优化计算,因为它们没有使用,并且main只会返回0.

If you turn on optimization (-O3) then the calculations are simply optimized away because they are not used, and main just returns 0.

如果您创建一个执行一些浮点计算并返回浮点数或双精度数的函数,并且在启用优化的情况下进行编译,那么您会看到浮点常量存储在静态内存中.

If you make a function that does some floating point calculations and returns a float or double, and compile with optimization on, then you will see that the floating point constants are stored in static memory.

我尝试过:

float test(float x) {
    return x*0.9f + 3.1f;
}

g ++ -c -S -O3 test.cpp

g++ -c -S -O3 test.cpp

cat test.s

cat test.s

并得到:

mulss   .LC0(%rip), %xmm0
addss   .LC1(%rip), %xmm0
ret

其中.LC0和.LC1是只读数据段中的常量.x86和x86-64指令集没有(不幸的)没有指令将立即数存储在浮点寄存器或向量寄存器中.它必须首先将常量存储在通用寄存器中,然后将其传输到xmm寄存器中,这不是最佳选择(除非数据高速缓存上的负载很重,而代码高速缓存上的负载很重).

where .LC0 and .LC1 are constants in the read-only data segment. The x86 and x86-64 instruction set has (unfortunately) no instruction that stores an immediate constant in a floating point register or vector register. It would have to first store the constant in general purpose registers and then transfer it to an xmm register, and this is not optimal (except for cases where there is heavy load on the data cache but not on the code cache).

这篇关于C ++浮点常量是否总是存储在静态内存中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆