gpt4 book ai didi

c++ - 结构的 CPU 开销?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:18:53 25 4
gpt4 key购买 nike

在 C/C++ 中,与孤立变量相比,访问结构成员是否有任何 CPU 开销?

举个具体的例子,像下面第一个代码示例这样的东西应该比第二个使用更多的 CPU 周期吗?如果它是一个类而不是一个结构会有什么不同吗? (在 C++ 中)

1)

struct S {
int a;
int b;
};

struct S s;
s.a = 10;
s.b = 20;
s.a++;
s.b++;

2)

int a;
int b;
a = 10;
b = 20;
a++;
b++;

最佳答案

“先不要优化。”编译器会找出最适合你的情况。先写有意义的东西,如果需要的话,稍后再写得更快。为了好玩,我在 Clang 3.4 (-O3 -S) 中运行了以下命令:

void __attribute__((used)) StructTest() {
struct S {
int a;
int b;
};

volatile struct S s;
s.a = 10;
s.b = 20;
s.a++;
s.b++;
}
void __attribute__((used)) NoStructTest() {
volatile int a;
volatile int b;
a = 10;
b = 20;
a++;
b++;
}

int main() {
StructTest();
NoStructTest();
}

StructTestNoStructTest 具有相同的 ASM 输出:

pushl   %ebp
movl %esp, %ebp
subl $8, %esp
movl $10, -4(%ebp)
movl $20, -8(%ebp)
incl -4(%ebp)
incl -8(%ebp)
addl $8, %esp
popl %ebp
ret

关于c++ - 结构的 CPU 开销?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22311131/

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