Can __attribute__((packed)) affect the performance of a program?(__attribute__((packed)) 会影响程序的性能吗?)
问题描述
我有一个名为 log 的结构,其中有 13 个字符.做了一个sizeof(log)后发现大小不是13而是16.我可以用__attribute__((packed))把它变成13的实际大小,但是我想知道这是否会影响程序的性能.这是一个使用频率很高的结构.
I have a structure called log that has 13 chars in it. after doing a sizeof(log) I see that the size is not 13 but 16. I can use the __attribute__((packed)) to get it to the actual size of 13 but I wonder if this will affect the performance of the program. It is a structure that is used quite frequently.
我希望能够读取结构的大小(13 不是 16).我可以使用宏,但如果此结构发生更改,即添加或删除字段,我希望在不更改宏的情况下更新新大小,因为我认为这很容易出错.有什么建议吗?
I would like to be able to read the size of the structure (13 not 16). I could use a macro, but if this structure is ever changed ie fields added or removed, I would like the new size to be updated without changing a macro because I think this is error prone. Have any suggestion?
推荐答案
是的,会影响程序的性能.添加填充意味着编译器可以使用整数加载指令从内存中读取内容.如果没有填充,编译器必须单独加载内容并进行位移以获得整个值.(即使是 x86 并且这是由硬件完成的,它仍然必须完成).
Yes, it will affect the performance of the program. Adding the padding means the compiler can use integer load instructions to read things from memory. Without the padding, the compiler must load things separately and do bit shifting to get the entire value. (Even if it's x86 and this is done by the hardware, it still has to be done).
考虑一下:如果不是出于性能原因,编译器为什么会插入随机的、未使用的空间?
Consider this: Why would compilers insert random, unused space if it was not for performance reasons?
这篇关于__attribute__((packed)) 会影响程序的性能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:__attribute__((packed)) 会影响程序的性能吗?
基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
