Johan Kotlinski
Johan Kotlinski

Reputation: 25769

How to get number of physical CPU:s in Linux using C?

I am aware that sysconf(_SC_NPROCESSORS_ONLN) will give me the number of logical processors. But how can I get the number of physical processors?

Upvotes: 4

Views: 3262

Answers (4)

Mark Drago
Mark Drago

Reputation: 2066

I think the best way to get this information is to use hwloc: http://www.open-mpi.org/projects/hwloc/.

They provide a bunch of user tools that let you get at the cpu topology of a system, but they also provide a library that you can use from C: http://www.open-mpi.org/projects/hwloc/doc/v1.1.1/#interface

Upvotes: 1

adobriyan
adobriyan

Reputation: 2662

@Havoc P: offline cpus aren't shown in /proc/cpuinfo .

CPU topology is described by /sys/devices/system/cpu/cpu*/topology/*

Upvotes: 3

Havoc P
Havoc P

Reputation: 8477

You could parse /proc/cpuinfo and count the number of distinct "physical id:" lines. Sort of annoying, but I don't know if there's a better option. If you're using GLib or another library with regex support it'd be easier. Or you could popen() a command line to do it if you're feeling really hacky. example command line at: http://www.brandonhutchinson.com/Understanding_proc_cpuinfo.html

Upvotes: 1

schnaader
schnaader

Reputation: 49747

Perhaps this answer to a similar question does help. There's a comment about the code not being correct, but it could be a good starting point.

Upvotes: 0

Related Questions