3

In my server, there exists several CPUs (0-7). I need run parallel code, and each process affiliate with one CPU, so how do I know the CPU information for each process?

For example, if two processes (#0 and #1) exist, and process #0 uses CPU 5 and process #1 uses CPU 7.

how do I know that by programming in C or Fortran?

5 Answers 5

2

Use the sched_getcpu() call.

Keep in mind that a process/thread can be scheduled freely to run on any available cpu/core, so one of your processes could run on core 1 one second, and on core 2 the next milisecond. You can restrict which processors a process is allowed to run on with sched_setaffinity()

2

I'm not aware of any system call on Linux that will give you general information about what CPU a thread in running on. @nos is correct that sched_getcpu() will tell you which CPU a thread is running on, but only for the calling context.

You can do this by querying the /proc file system. However, if you find yourself building your application around this functionality, it is likely that you need to reexamine your design.

The file /proc/<pid>/stats contains a field that provides you with the last CPU the process ran on. You would just need to parse the output. (use man proc to see the field list).

1

In general it is the task of the operating system to abstract such things from applications. Normally I see my applications (as simple as doing a grep on a huge file) change CPU core every once in a while.

Now if you want to force an application on a specific core you can manually set the CPU affinity.

I've written some pretty strange software in the past and I've never had the desire to know and/or control this.

Why would you want to know?

0

More generally, why do you want to know? The Linux kernel is very good at scheduling processes/threads to make the best use of the available cores.

1
  • since I want to change the cpu speed dynamically and do some research work Aug 3, 2010 at 20:23
0

Generally, you have to change the CPU affinity, because a process can migrate between processors: CPU Affinity (Linux Journal, 2003).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.