gpt4 book ai didi

c++ - C++ 枚举使用起来比整数慢吗?

转载 作者:IT老高 更新时间:2023-10-28 12:12:13 25 4
gpt4 key购买 nike

这真的是一个简单的问题:

我正在编写一个 Go 程序。我应该用 QVector<int> 代表董事会吗?或 QVector<Player>在哪里

enum Player
{
EMPTY = 0,
BLACK = 1,
WHITE = 2
};

我想当然,使用 Player 而不是整数会更慢。但我想知道还有多少,因为我相信使用 enum更好的编码。

我已经做了一些关于分配和比较玩家的测试(而不是 int)

QVector<int> vec;
vec.resize(10000000);
int size = vec.size();


for(int i =0; i<size; ++i)
{
vec[i] = 0;
}


for(int i =0; i<size; ++i)
{
bool b = (vec[i] == 1);
}


QVector<Player> vec2;
vec2.resize(10000000);
int size = vec2.size();


for(int i =0; i<size; ++i)
{
vec2[i] = EMPTY;
}


for(int i =0; i<size; ++i)
{
bool b = (vec2[i] == BLACK);
}

基本上,它只慢了 10%。在继续之前还有什么我应该知道的吗?

谢谢!

编辑:10% 的差异不是我的想象,它似乎特定于 Qt 和 QVector。当我使用std::vector时,速度是一样的

最佳答案

枚举在编译时被完全解析(枚举常量作为整数文字,枚举变量作为整数变量),使用它们没有速度损失。

一般来说,平均枚举不会有一个大于 int 的底层类型(除非你在其中放入非常大的常量);事实上,在 §7.2 ¶ 5 中明确指出:

The underlying type of an enumeration is an integral type that can represent all the enumerator values defined in the enumeration. It is implementation-defined which integral type is used as the underlying type for an enumeration except that the underlying type shall not be larger than int unless the value of an enumerator cannot fit in an int or unsigned int.

您应该在适当的时候使用枚举,因为它们通常使代码更易于阅读和维护(您是否尝试过调试充满“魔数(Magic Number)”的程序?:S)。

至于你的结果:可能你的测试方法没有考虑到你在“正常”机器上运行代码时的正常速度波动1;您是否尝试过多次(100+)次运行测试并计算您的时间的平均值和标准偏差?结果应该是兼容的:均值之间的差异不应大于两个标准差的 RSS2 的 1 或 2 倍(通常假设波动的高斯分布)。

您可以做的另一项检查是比较生成的汇编代码(使用 g++,您可以通过 -S 开关获得它)。


  1. 在“正常”PC 上,由于其他任务正在运行、缓存/RAM/VM 状态等原因,您会出现一些不确定的波动......
  2. Root Sum Squared,标准差平方和的平方根。

关于c++ - C++ 枚举使用起来比整数慢吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4851810/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com