Search code examples
clinuxbsd

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.


Solution

  • 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