Griwes
Griwes

Reputation: 9049

Getting number of cores (*not* HT threads)

I have tried sysconf(_SC_NPROCESSORS_ONLN) and sysconf(_SC_NPROCESSORS_CONF), but they both return total number of (as Intel calls it in their CPU documentation) Threads (as in: hyper-threading threads), not physical cores (called Core on mentioned Intel site).

Is there a way to get number of physical cores, instead of logical? Counting entries in /proc/cpuinfo gives 8, similarly to calling sysconf, and my processor is the one linked above.

I'm interested in answers working on Linux and BSDs, preferably in form of C API.

Upvotes: 5

Views: 3689

Answers (3)

Douglas B. Staple
Douglas B. Staple

Reputation: 10946

A different solution is to use hwloc. Here's a simple example:

#include <hwloc.h>
#include <stdio.h>

int main(){

  // Allocate, initialize, and perform topology detection
  hwloc_topology_t topology;
  hwloc_topology_init(&topology);
  hwloc_topology_load(topology);

  // Try to get the number of CPU cores from topology
  int depth = hwloc_get_type_depth(topology, HWLOC_OBJ_CORE);
  if(depth == HWLOC_TYPE_DEPTH_UNKNOWN)
    printf("*** The number of cores is unknown\n");
  else
    printf("*** %u core(s)\n", hwloc_get_nbobjs_by_depth(topology, depth));

  // Destroy topology object and return
  hwloc_topology_destroy(topology);
  return 0;
}

I tested this on a Linux box running Red Hat 4.1.2-48 with GCC 4.1.2, and also on an Apple running OS X 10.8.1 with GCC 4.2.1

Upvotes: 7

twalberg
twalberg

Reputation: 62509

The files in /sys/devices/system/cpu/cpu<n> are much easier to parse for this sort of information, and include additional information about topology. It's still not a pre-wrapped API, but if all you're looking for is CPU count and possibly which threads belong to which cores belong to which chips, writing something to parse this would be not too bad. I know there are some libraries (e.g. the cgroups stuff) that already parse this, so there are reference points to find good ways to go about it, and there might even be a way to just use parts of those libraries if you want.

Upvotes: 2

liori
liori

Reputation: 42377

It is not a C API, and it probably works only on Linux. But this is all I know, maybe you'll find this useful.

/proc/cpuinfo's CPU descriptions have few fields: physical id, which is a physical CPU identifier and core id, which is the physical core identifier. If you calculate number of unique (physical id, core id) pairs, you'll get what you want.

You can also check the cpu cores field for each physical CPU listed.

Upvotes: 4

Related Questions