c++ - 为什么快速整数类型比其他整数类型快?

标签 c++ c performance types int

在 ISO/IEC 9899:2018 (C18) 中,它在 7.20.1.3 下说明:

7.20.1.3 Fastest minimum-width integer types

1 Each of the following types designates an integer type that is usually fastest268) to operate with among all integer types that have at least the specified width.

2 The typedef name int_fastN_t designates the fastest signed integer type with a width of at least N. The typedef name uint_fastN_t designates the fastest unsigned integer type with a width of at least N.

3 The following types are required:

int_fast8_t, int_fast16_t, int_fast32_t, int_fast64_t, uint_fast8_t, uint_fast16_t, uint_fast32_t, uint_fast64_t

All other types of this form are optional.


268) The designated type is not guaranteed to be fastest for all purposes; if the implementation has no clear grounds for choosing one type over another, it will simply pick some integer type satisfying the signedness and width requirements.



但是没有说明为什么这些“快速”整数类型更快。
  • 为什么这些快速整数类型比其他整数类型快?


  • 我用C++标记了这个问题,因为在cstdint的头文件中,C++17中也提供了快速整数类型。 .不幸的是,在 ISO/IEC 14882:2017 (C++17) 中没有关于它们的解释的这样的部分;我已经在问题正文中以其他方式实现了该部分。

    信息:在C中,它们在stdint.h的头文件中声明。 .

    最佳答案

    想象一个只执行 64 位算术运算的 CPU。现在想象一下如何在这样的 CPU 上实现无符号 8 位加法。要获得正确的结果,必然会涉及多个操作。在这样的 CPU 上,64 位操作比其他整数宽度上的操作快。在这种情况下,所有Xint_fastY_t可能是 64 位类型的别名。

    如果 CPU 支持窄整数类型的快速操作,因此较宽的类型并不比较窄的类型快,则 Xint_fastY_t不会(不应该)是比表示所有 Y 位所需的更宽类型的别名。

    出于好奇,我检查了某些架构上特定实现(GNU、Linux)的大小。这些在同一架构上的所有实现中并不相同:

    ┌────╥───────────────────────────────────────────────────────────┐
    │ Y  ║   sizeof(Xint_fastY_t) * CHAR_BIT                         │
    │    ╟────────┬─────┬───────┬─────┬────────┬──────┬────────┬─────┤
    │    ║ x86-64 │ x86 │ ARM64 │ ARM │ MIPS64 │ MIPS │ MSP430 │ AVR │
    ╞════╬════════╪═════╪═══════╪═════╪════════╪══════╪════════╪═════╡
    │ 8  ║ 8      │ 8   │ 8     │ 32  │ 8      │ 8    │ 16     │ 8   │
    │ 16 ║ 64     │ 32  │ 64    │ 32  │ 64     │ 32   │ 16     │ 16  │
    │ 32 ║ 64     │ 32  │ 64    │ 32  │ 64     │ 32   │ 32     │ 32  │
    │ 64 ║ 64     │ 64  │ 64    │ 64  │ 64     │ 64   │ 64     │ 64  │
    └────╨────────┴─────┴───────┴─────┴────────┴──────┴────────┴─────┘
    

    请注意,虽然对较大类型的操作可能更快,但此类类型也会占用更多缓存空间,因此使用它们不一定会产生更好的性能。此外,人们不能总是相信实现首先做出了正确的选择。与往常一样,为了获得最佳结果,需要进行测量。

    表格截图,适用于安卓用户:

    Screenshot of above table

    (Android 没有单色字体中的框绘图字符 - ref)

    关于c++ - 为什么快速整数类型比其他整数类型快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59593541/

    相关文章:

    C++循环条件不会结束循环

    c - C 程序执行卡住

    java - Socket通信,Java客户端C服务器

    performance - AppFabric缓存-正确使用DataCacheFactory和DataCache

    Java:执行连接变量和文字的 StringBuilder.indexOf() 的开销

    performance - Spring安全访问控制列表数十亿行

    c++ - 透明QLabel

    不需要括号或引用的成员别名的 C++ 标准方式?

    C++ 和成员函数指针

    c - 如何查找表达式的哪个索引与正则表达式匹配