Get Your Program to Execute on a Specific CPU

Most systems these days have multiple cores.
In linux you can determine how many cores are present from
the following file

$ cat /proc/cpuinfo

Each core will have an entry and will be labeled starting from 0.
(in my quad core the core's are
processor 0, processor 1, processor 2, processor 3)

When you execute  a program it gets scheduled into any one of these
processors. In case you want to specify which processor you want your
program to run, then use the sched_setaffinity call.

A simple example for using this call is shown below:



int main(int argc, char **argv)
{
    unsigned long mask;
    mask = 0x2;
    if (sched_setaffinity(0, sizeof(mask), &mask) <0) {
        perror("sched_setaffinity");
    }
    sleep(1000);
}

You may have to include 'sched.h'  to get it to compile

The mask will tell which processors the program can execute in.
For example a mask of 0x2 (in binary : 0010) means processor 1.
Similary a mask of 0x1 (0001) means processor 0.

You can check which cpu is executing your program by
running top and then pressing 1.








No comments:

Post a Comment

Followers