1

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?

4

4 に答える 4

6

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.

于 2013-02-11T02:25:39.677 に答える
5

Just return j from your function and do something with it in the caller. But this is a bad way to stress out a processor because it loads only a very limited subset of the processor. Depending on why you want the load the processor (Do you want to make sure it's working? Do you want to heat it as much as possible?) you should pick a program specifically designed to do what you want. Prime95 is a common one.

于 2013-02-11T02:41:00.613 に答える
4

Try using the 'volatile' keyword on your variables. This is ofcourse, ignoring the fact that you'd need to do a lot more to stress out your computer. You might find this answer useful, though I would take the warning on that code very seriously.

于 2013-02-11T02:25:18.943 に答える
2

If you really want to stress the processor:

tan(atan(tan(atan(tan(atan(tan(atan(tan(atan(tan(atan(tan(atan(tan(atan(tan(atan(tan(atan(tan(atan(0.5d))))))))))))))))))))));

Add a whole lot more levels, and put it into a loop.

This was a soak-test for the PDP-11 many years ago.

于 2013-02-12T00:08:51.783 に答える