简体   繁体   English

gcc中的编译器优化

[英]Compiler optimizations in gcc

I have a code in C and I am running some tests. 我有一个C代码,我正在运行一些测试。 I need to access an array, but in "read-only" mode. 我需要访问一个数组,但是在“只读”模式下。 I am doing something like this: 我正在做这样的事情:

for (int i= 0; i < 1000; i++){
    int a = shared_array[rand() % 64];
    int b = shared_array[rand() % 64];
}

My question is: How can I fetch a value from memory and be sure that the compiler is not optimizing it by removing these instructions, given that in my test I am doing nothing with those values. 我的问题是:如何从内存中获取值并确保编译器没有通过删除这些指令来优化它,因为在我的测试中我对这些值没有任何作用。 Even if I add an operation int v = a + b , again v is not used anywhere else, so it could be ignored. 即使我添加了一个操作int v = a + b ,也不会在其他任何地方使用v ,因此可以忽略它。

I am using gcc with -O3, and I need to do it that way to be able to compare it against results from another source. 我正在使用gcc和-O3,我需要这样做才能将它与来自其他来源的结果进行比较。

The typical way you force the compiler to actually read an otherwise unused variable is to make it volatile . 强制编译器实际读取其他未使用的变量的典型方法是使其volatile This should guarantee the compiler actually read/write the variable from RAM when it is used. 这应该保证编译器在使用时实际从RAM读取/写入变量。

在当前编译单元(源文件)中未定义的函数中使用ab

The keyword volatile tells the compiler to not optimize that code. 关键字volatile指示编译器不优化该代码。 This applies for both variables and functions. 这适用于变量和函数。 You can even do this on inline assembly, which is a more advanced topic. 您甚至可以在内联汇编中执行此操作,这是一个更高级的主题。 See this question . 看到这个问题

It is usually applied after the type specifier, eg int volatile i = 0; 它通常在类型说明符之后应用,例如int volatile i = 0; .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM