位域及其效率

头一次听说C中的 位域bit fields  好高端的用法

比如

***********************TCP的结构****************************
struct tcphdr
{
    u_int16_t source;
    u_int16_t dest;
    u_int32_t seq;
    u_int32_t ack_seq;
# if __BYTE_ORDER == __LITTLE_ENDIAN
    u_int16_t res1:4;
    u_int16_t doff:4;
    u_int16_t fin:1;
    u_int16_t syn:1;
    u_int16_t rst:1;
    u_int16_t psh:1;
    u_int16_t ack:1;
    u_int16_t urg:1;
    u_int16_t res2:2;
# elif __BYTE_ORDER == __BIG_ENDIAN
    u_int16_t doff:4;
    u_int16_t res1:4;
    u_int16_t res2:2;
    u_int16_t urg:1;
    u_int16_t ack:1;
    u_int16_t psh:1;
    u_int16_t rst:1;
    u_int16_t syn:1;
    u_int16_t fin:1;
# else
#   error "Adjust your <bits/endian.h> defines"
# endif
    u_int16_t window;
    u_int16_t check;
    u_int16_t urg_ptr;
};

使用位域可以有效的节省内存,比如在结构体中

struct 
{
unsigned int sex:1;
unsigned int age:7;
};
相当于sex占了unsigned int的一位,age占了七位。

虽然节省了内存,不过效率会不会降低呢?


实践证明,使用位域可以节省时间,或者说和不使用时大体相当(比如int i:32;);只有一种情况下会比普通情况慢,就是在使用的位数跨越高16位和低16位的时候(针对int的32位)。

理由?


网上有一些说法,有待证实——

"大家都知道,结构体成员的对齐是为了提高访问数据的效率;而位域成员显然没有进行结构体对齐,这样对数据访问的效率存在影响吗? 
理所当然 (应该是我想当然)这样会降低效率;然而,我看了一些网页上的资料(我没有进行仔细的分析,只是借用别人的结论);对位域成员的访问在编译阶段进行了优化;从生成的汇编源代码看出效率是一样的,并没有降低!"  ---http://www.xuebuyuan.com/1119178.html


"If you use bit-fields for anything other than assembling (or disassembling) structures at some physical interface, performance may suffer. This is because every time you read or write from a bit-field, the compiler will have to generate code to do the masking and shifting, which will burn cycles"

" I would imagine that in most circumstances, using int would be fastest, because it's the platform's native width. The exception to this would be if doing everything as int makes your data structures significantly bigger, causing cache misses, etc."

"Computers may have more RAM these days, but keeping memory usage lower can help to keep it within the CPU memory cache, which would increase performance. On the other hand, bitfields require more instructions to access them, which decreases performance. Which is more significant?"

---http://stackoverflow.com/questions/4240974/when-is-it-worthwhile-to-use-bit-fields


参考:

C语言如何获得精确到毫秒的时间

http://blog.csdn.net/witxjp/article/details/8079751

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值