I’m using GCC on ununtu 14.04. My program is written in c++ and in a case i need to check the amount of time the program needs to read a large integer array. what is the best way to do this without causing unnecessary compiler optimization?
10
It will optimize the reads out if it sees the result is unused, even more if the compiler sees the entire loop body is empty the entire loop may become optimized away.
You will need to do another operation with the result to ensure the reads remain. Xoring the integers together is a simple example, calling a function with it as a parameter that the compiler can’t optimize away (because it may have side effects).
Having said all that just reading the array is not a useful metric in itself.
1
Unless I am misunderstanding your requirements, the ‘volatile’ keyword may be sufficient for your desire to prevent undesired optimization. I tested the following using GCC version 4.6.3 and verified the reading of the array elements into x was never optimized away (tested with -O0, -O1, -O2 and -O3 optimization levels).
#include <stdio.h>
int array[1024];
int main (void) {
volatile int x;
int i;
for (i = 0; i < 1024; i++) {
x = array[i];
}
return 0;
}
I hope this helps.