Ben Ben - 29 days ago 12
C++ Question

Code stolen by the compiler, how do I circumvent its criminal ways

I wanted to stress out the processor on a new computer at work. I figured a good way to do it would be to open a thread for each processor with the function:

void soStressful() {
int j = 0;
for (int i = 0; i < 10000; ++i) {
j += i;
}
}


But for some reason the compiler takes this code away. (Because the program runs instantly regardless of the complexity of the calculation or the size of i) and we also log very little cpu usage.

How can I stop the compiler for compiling out this code?

Answer

Your function takes no inputs and provides no outputs. So the compiler easily figures out that it does nothing.

I suggest that in your loop you modify a global variable, preferably declared volatile. Then the compiler will not be able to assume that it is not used.

Also, if the processor is fast, you'll need more than a 10000 iteration loop to get any meaningful CPU usage.

You might want to look at some of the benchmarking code out there - dhrystone is one.

Comments