c++ - 是否有任何与可读性无关的原因不能每次都专门使用固定宽度的整数?

标签 c++ c

假设我们有 uint_least8_t var,其中,假设地说,var 永远不会超过值 255。 我知道这不是编程的工作方式,“可能”和“曾经”是一种亵渎,但是,除了使代码复杂化并降低其可读性之外,是什么让始终使用固定宽度整数成为一个坏主意?

最佳答案

性能是另一个原因。

窄操作数需要额外的缩小/扩大指令。这不能总是在没有副作用的情况下被优化掉。有时,优化器不够智能,无法安全运行。

以下面这个人为的例子为例。

#include <iostream>
#include <chrono>

using namespace std;
using namespace std::chrono_literals;

int main()
{
    auto tm1 = chrono::high_resolution_clock::now();
    unsigned int n = 0;
    unsigned int x = 0;  // though, uint8_t would have been enough!
    for (unsigned int i = 0; i < 1000000000; i++) {
        n += (x * i);
        x = (n + 1) & 0x7F;
    }
    auto tm2 = chrono::high_resolution_clock::now();
    cout << n << ", " << (tm2 - tm1) / 1.0s << " s" << endl;
}

如果我们将 x 的类型从 unsigned int 更改为 uint8_t,应用程序将变慢 15%(运行 2s 而不是 1.7s使用 GCC 7.2 -O3 完全优化编译时在 x86-64 上的时间。

32-bit 组装x:

.L2:
  imul eax, edx
  inc edx
  add ebx, eax
  lea eax, [rbx+1]
  and eax, 127
  cmp edx, 1000000000
  jne .L2

8-bit 组装x:

.L2:
  movzx eax, al    ; owww!
  imul eax, edx
  inc edx
  add ebp, eax
  lea eax, [rbp+1]
  and eax, 127
  cmp edx, 1000000000
  jne .L2

关于c++ - 是否有任何与可读性无关的原因不能每次都专门使用固定宽度的整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53637492/

相关文章:

c++ - 我如何获得代码::blocks to keep the libraries configured after code::blocks restarts?

c++11 获取第一个(第二个等...)参数的类型,类似于 result_of

c++ - 作者基于 union 的可选 <bool> 实现在 P2641 中定义良好吗?

c - c 的 displayArray 函数

c++ - TRUE 和 FALSE 宏的奇怪定义

c - 如果在头文件中声明函数,C 中的单独编译会出错

c++ - 字符串构造函数的无限精度和指定的舍入和比例

c++ - 使用 QPixmap 填充 QWidget 的有效方法

c - 动态字符数组大小调整

c - C中函数的奇怪声明和定义