__attribute__((packed)) 会影响程序的性能吗? [英] Can __attribute__((packed)) affect the performance of a program?

查看:20
本文介绍了__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)) 会影响程序的性能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆