【问题标题】:declare static variable performance声明静态变量性能
【发布时间】:2021-07-06 15:34:39
【问题描述】:

在 C Linux 中,我可以将变量声明为静态到函数中,并且它只初始化一次,每次 CPU 再次看到该声明时,它将被跳过,或者全局声明

其中一个功能会有更好的性能吗?

void increase_x()
{
    static int x =0;
    x+=1;
}


static int x = 0 ;
void increase_x()
{
    x+=1;
}

【问题讨论】:

  • 在编译的 C 实现中,CPU 看不到声明。源代码被翻译成指令,进行翻译的编译器通过将静态声明构建到程序的数据中来处理它们,而不是提供它需要跳过的 CPU 指令。

标签: c linux performance gcc static


【解决方案1】:

没有区别。您甚至可以在编译代码的反汇编差异中看到这一点:

< localstatic:     file format elf64-x86-64
---
> globalstatic:     file format elf64-x86-64
107c107
<     1131:     8b 05 dd 2e 00 00       mov    0x2edd(%rip),%eax        # 4014 <x.0>
---
>     1131:     8b 05 dd 2e 00 00       mov    0x2edd(%rip),%eax        # 4014 <x>
109c109
<     113a:     89 05 d4 2e 00 00       mov    %eax,0x2ed4(%rip)        # 4014 <x.0>
---
>     113a:     89 05 d4 2e 00 00       mov    %eax,0x2ed4(%rip)        # 4014 <x>

【讨论】:

    【解决方案2】:

    两个版本之间的运行时性能应该相同。

    但是,在第一个 sn-p 中,x 仅在 increase_x 的主体内可见 - 程序的其余部分无法使用它的值。

    您可以更改increase_x 以返回x 的新值:

    int increase_x()
    {
      static int x = 0;
      return x += 1;
    }
    

    不过,这取决于您打算如何使用 x 的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多