3

I have a code in C and I am running some tests. 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.

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.

ees_cu
  • 800
  • 1
  • 9
  • 20
  • You could of course add them to an accumulator declared outside the loop, so that each iteration does have an impact on the result. – Magnus Reftel Apr 25 '14 at 13:02
  • not related to the question, but replacing `% 64` with `& 63` may improve performance a bit (if it's not hidden by memory latency). Also - this doesn't guarantee uniform distribution. – Leeor Apr 26 '14 at 13:15

3 Answers3

6

The typical way you force the compiler to actually read an otherwise unused variable is to make it volatile. This should guarantee the compiler actually read/write the variable from RAM when it is used.

rubenvb
  • 74,642
  • 33
  • 187
  • 332
  • 3
    It _is_ guaranteed to work by the C standard. Whether or not GCC follows the C standard is another matter. – Lundin Apr 25 '14 at 12:52
  • @Jens indeed, it is a C++ concept. Didn't notice this was a C question. I removed the confusion `:-)`. – rubenvb Apr 25 '14 at 13:03
1

Use a and b in a function that is not defined in your current compilation unit (source file).

doron
  • 27,972
  • 12
  • 65
  • 103
0

The keyword volatile tells the compiler to not optimize that code. 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, e.g. int volatile i = 0;.

Community
  • 1
  • 1
no92
  • 129
  • 2
  • 13