在 32 位 CPU 上,“整数"类型是否比“短"类型更有效? [英] On 32-bit CPUs, is an 'integer' type more efficient than a 'short' type?

查看:20
本文介绍了在 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 上,“整数"类型是否比“短"类型更有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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