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
from的类型更改unsigned int
为uint8_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
推荐阅读
- python - 如何根据 pandas 或 numpy 中的条件从数组中提取值?
- php - 我如何使用 Model::factory() 更新用户积分
- javascript - 使用 bbox 策略强制刷新 openlayers 5.3 集群源
- karate - 我打算中止场景,但是,场景和功能被报告为失败
- javascript - 从树莓派网络服务器发送 CAN-BUS 消息
- ios - iOS是否内置了时间序列平滑,比如内核或高斯?(也许在 CoreImage 或 CoreAudio 中?)
- objective-c - 将 MAX 与 unsigned long 和 unsigned long 减法一起使用
- python - 在模板中显示 Django TextField (Django 2+)
- javascript - 在 TinyMCE 编辑器中使用 PHP 在服务器上上传图像
- amazon-web-services - 无法从 ecs-agent 访问 AWS ECS VPC 终端节点