Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 542
efunneko Avatar asked Jan 29 '09 13:01

efunneko


People also ask

How do I find my CPU cores?

Press Ctrl + Shift + Esc to open Task Manager. Select the Performance tab to see how many cores and logical processors your PC has.

What is CPU core in Linux?

Here, the CPU(s) value indicates the number of logical cores, which is equal to 8 in our output. The number of logical cores is equal to “Thread(s) per core” × “Core(s) per socket” × “Socket(s)” and the number of physical cores on a machine equals “Core(s) per socket” × “Socket(s)”.


1 Answers

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.

like image 182
Johannes Schaub - litb Avatar answered Nov 03 '22 11:11

Johannes Schaub - litb