c++ - 内置式效率

标签 c++ performance built-in

最高效的类型下第二here

...and when defining an object to store a floating point number, use the double type, ... The double type is two to three times less efficient than the float type...

好像自相矛盾?

而且我在其他地方(不记得在哪里)读到涉及 int 的计算在许多机器上比 short 更快,因为它们被转换为 int 来执行操作?这是真的?有这方面的链接吗?

最佳答案

人们总是会争论您链接到的网站上内容的质量。但是你提到的两个引号:

...and when defining an object to store a floating point number, use the double type, ...

... The double type is two to three times less efficient than the float type...

指的是两个不同的东西,第一个暗示使用 double 会因为精度的提高而产生的问题少得多,而另一个则谈论性能。但老实说,我不会太在意这一点,如果您的代码表现不佳,那很可能是由于算法选择不正确,而不是原始数据类型选择错误。

这里引用了我的一位老师关于单精度和 double float 性能比较的引述:Agner Fog,他在他的网站上有很多有趣的读物:http://www.agner.org关于软件优化,如果您真的对微优化感兴趣,请看一看:

In most cases, double precision calculations take no more time than single precision. When the floating point registers are used, there is simply no difference in speed between single and double precision. Long double precision takes only slightly more time. Single precision division, square root and mathematical functions are calculated faster than double precision when the XMM registers are used, while the speed of addition, subtraction, multiplication, etc. is still the same regardless of precision on most processors (when vector operations are not used).

来源: http://agner.org/optimize/optimizing_cpp.pdf

虽然不同的编译器和不同的处理器可能会有不同的变化,但应该从中吸取的教训是,您很可能不需要担心这一级别的优化,看看算法的选择,甚至是数据容器,而不是原始数据类型。

关于c++ - 内置式效率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26683444/

相关文章:

c++ - 从 catch block 中的函数重新抛出

ios - UITableView 重新加载数据很慢

c# - 适用于字节数组的哈希码方法?

performance - 汇编-如何通过延迟和吞吐量对CPU指令进行评分

c - 可能(x)和 __builtin_expect((x),1)

C++ 从 txt 读取数字直到换行(逻辑回归)

c++ - GCC '-g' 选项有什么作用?

c++ - (a==1 && a==2 && a==3) 可以在 C 或 C++ 中评估为真吗?

python - 主循环 'builtin_function_or_method' 对象不可迭代

python - 如何在 pickle 加载期间用 None 替换导致导入错误的对象?