首页 > 解决方案 > 是否有任何与可读性无关的原因不每次都专门使用固定宽度的整数?

问题描述

假设我们有uint_least8_t var, 假设var它永远不会超过值 255。我知道这不是编程的工作方式,“可能”和“永远”是一种亵渎,但是,除了使代码复杂化和制作它可读性较差,是什么让总是使用固定宽度的整数成为一个坏主意?

标签: c++c

解决方案


性能是另一个原因。

窄操作数需要额外的缩小/扩大指令。这不能总是在没有副作用的情况下被优化掉。有时优化器只是不够聪明并且不够安全。

举一个人为的例子。

#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;
}

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

使用32 位 进行组装x

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

8 位 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

推荐阅读