How can I get the CPU core number from within a user-space app (Linux, C)?

efunneko picture efunneko · Jan 29, 2009 · Viewed 14.1k times · Source

Presumably there is a library or simple asm blob that can get me the number of the current CPU that I am executing on.

Answer

Johannes Schaub - litb picture Johannes Schaub - litb · Jan 29, 2009

Use sched_getcpu to determine the CPU on which the calling thread is running. See man getcpu (the system call) and man sched_getcpu (a library wrapper). However, note what it says:

The information placed in cpu is only guaranteed to be current at the time of the call: unless the CPU affinity has been fixed using sched_setaffinity(2), the kernel might change the CPU at any time. (Normally this does not happen because the scheduler tries to minimize movements between CPUs to keep caches hot, but it is possible.) The caller must be prepared to handle the situation when cpu and node are no longer the current CPU and node.