• Linux c 内存高速访问


    概述

    要想高速利用内存就必须高效利用cpu cache,关于cpu cache这里就不多加讨论了,自己感兴趣可以google

    而cpu访问内存的单位是cache line,因此高效利用cache line是写c程序的必要条件

    __attribute__ 作用于结构体内部变量

      3 struct foo{
      4         int a;
      5 
      6         char b;// __attribute__((aligned(64)));
      7 
      8 //      char c;
      9 };//__attribute__((aligned(64)));
     10 int main()
     11 {
     12         struct foo foo;
     13         printf("%d
    ",(sizeof(struct foo)));
     14         return 0;
     15 }

    输出为8,因为编译器会默认对结构体中的每个元素做对齐,而对其单位为结构体中占字节最多的变量

      3 struct foo{
      4         int a;
      5 
      6         char b __attribute__((aligned(64)));
      7 
      8 //      char c;
      9 };//__attribute__((aligned(64)));
     10 int main()
     11 {
     12         struct foo foo;
     13         printf("%d
    ",(sizeof(struct foo)));
     14         return 0;
     15 }

    输出为128,因为__attribute__作用于结构体内部变量时会把该变量与结构体首地址的偏移设置为64的倍数,

    即b-a的地址偏移为64,而编译器会默认对结构体中的每个元素做对齐,而本例中在编译器看来

    变量a占的内存空间为64字节,因此输出为128

      3 struct foo{
      4         int a;
      5 
      6         char b __attribute__((aligned(64)));
      7 
      8         char c;
      9 };//__attribute__((aligned(64)));
     10 int main()
     11 {
     12         struct foo foo;
     13         printf("%d
    ",(sizeof(struct foo)));
     14         return 0;
     15 }

    输出仍为128,因为b只占用了1个字节,而结构体是按64字节对齐的,因此c-b地址偏移为1

    __attribute__ 作用于结构体

      3 struct foo{
      4         int a;
      5 
      6         char b ;//__attribute__((aligned(64)));
      7 
      8         char c;
      9 }__attribute__((aligned(64)));
     10 int main()
     11 {
     12         struct foo foo;
     13         printf("%d
    ",(sizeof(struct foo)));
     14         printf("%p
    ",(&foo));
     15         return 0;
     16 }

    输出

    64
    0x7fffd34de600

    当__attribute__作用于结构体时有两个作用,一个是让结构体的大小是64的倍数,另外一个作用

    是当在栈上分配结构时,结构体的首地址是64的倍数;如果在堆上分配结构体的话,则结构体的

    首地址不一定是64的倍数。

  • 相关阅读:
    python解析HTML的方法——HTMLParser
    使用python的nose模块进行测试
    python运行时修改代码的方法——monkey patch
    使用python的nose模块进行测试
    如何使用jquery是新tab形式
    table边框设置
    如何使用jquery是新tab形式
    table边框设置
    Notepad++安装Function list插件
    Notepad++安装Function list插件
  • 原文地址:https://www.cnblogs.com/scottieyuyang/p/6118812.html
Copyright © 2020-2023  润新知