开发者

Why is there a switch in the CPU core usage when I run this C code?

When I ran this code using gcc,

$ cat eatup.c
#include<stdio.h>
#include<stdlib.h>

int main() {
    int i = 0;
    while(1) {
        i++;
    }
}
$

the CPU graph went like this :

Why is there a switch in the CPU core usage when I run this C code?

I am not sure why there is a cross in the CPU core usage.

  • I started the run at the rise to the left of the 40 mark, then initially core2 usage rose to 100% but after sometime there was a switch and core1 usage went 100%.

  • Any subsequent runs have not reproduced the situation. All I get is a single rise

    Why is there a switch in the CPU core usage when I run this C code?

This might be a bit OS dependent (scheduling processes on the cores), but is there anything that could explain why the 开发者_开发百科switch happened (as shown in the first screenshot)? Any guesses?


Turns out these switches are not so uncommon. Here is a screenshot of System Monitor just after bootup (Ubuntu 10.04)

Full Size

Why is there a switch in the CPU core usage when I run this C code?


What may have happened, it that the OS had two other processes that needed to run. The first was given the second core (because you were on the first). The second caused your program to lose it's CPU core. Then the first thread released it's core, and your program was assigned to it.

I'm no linux guru but it is usually possible to tell the OS that you have a preferred core you want to run on.


This is OS-dependent, but normally no OS ever gives you guarantees that your thread will be run on the same core the whole time, unless you take specific steps to make it so.

While there are some obvious benefits in keeping a thread associated with the same core, there's nothing unusual in it being reassigned to another core from time to time. You might even see it getting thrown from core to core every time it gets to run (or almost every time). In fact, what you see in your tests looks pretty good in that respect.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜