在 32 位 CPU 上,“整数"类型是否比“短"类型更有效?

编程入门 行业动态 更新时间:2024-10-19 05:28:05
本文介绍了在 32 位 CPU 上,“整数"类型是否比“短"类型更有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在 32 位 CPU 上,一个整数是 4 个字节,一个短整数是 2 个字节.如果我正在编写一个使用许多数值的 C/C++ 应用程序,这些数值总是适合所提供的短整数范围,使用 4 字节整数还是 2 字节整数更有效?

On a 32-bit CPU, an integer is 4 bytes and a short integer is 2 bytes. If I am writing a C/C++ application that uses many numeric values that will always fit within the provided range of a short integer, is it more efficient to use 4 byte integers or 2 byte integers?

我听说 4 字节整数更有效,因为这适合从内存到 CPU 的总线带宽.但是,如果我将两个短整数相加,CPU 是否会在一次并行中打包这两个值(从而跨越总线的 4 字节带宽)?

I have heard it suggested that 4 byte integers are more efficient as this fits the bandwidth of the bus from memory to the CPU. However, if I am adding together two short integers, would the CPU package both values in a single pass in parallel (thus spanning the 4 byte bandwidth of the bus)?

推荐答案

是的,你绝对应该在 32 位 CPU 上使用 32 位整数,否则它可能最终屏蔽掉未使用的位(即,它总是会32 位的数学运算,然后将答案转换为 16 位)

Yes, you should definitely use a 32 bit integer on a 32 bit CPU, otherwise it may end up masking off the unused bits (i.e., it will always do the maths in 32 bits, then convert the answer to 16 bits)

它不会同时为您执行两个 16 位操作,但是如果您自己编写代码并且确定它不会溢出,那么您可以自己完成.

It won't do two 16 bit operations at once for you, but if you write the code yourself and you're sure it won't overflow, you can do it yourself.

编辑:我应该补充一点,这也取决于您对高效"的定义.虽然它能够更快地执行 32 位操作,但您当然会使用两倍的内存.

Edit: I should add that it also depends somewhat on your definition of "efficient". While it will be able to do 32-bit operations more quickly, you will of course use twice as much memory.

如果这些用于内部循环中的中间计算,则使用 32 位.但是,如果您是从磁盘读取它,或者即使您只需要为缓存未命中付出代价,使用 16 位整数可能仍然会更好.与所有优化一样,只有一种方法可以了解:分析.

If these are being used for intermediate calculations in an inner loop somewhere, then use 32-bit. If, however, you're reading this from disk, or even if you just have to pay for a cache miss, it may still work out better to use 16-bit integers. As with all optimizations, there's only one way to know: profile it.

更多推荐

在 32 位 CPU 上,“整数"类型是否比“短"类型更有效?

本文发布于:2023-11-25 22:55:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1631677.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   整数   更有效   CPU   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!