How to get the number of CPUs in Linux using C?

后端 未结 8 1689
情歌与酒
情歌与酒 2020-11-29 20:17

Is there an API to get the number of CPUs available in Linux? I mean, without using /proc/cpuinfo or any other sys-node file...

I\'ve found this implementation using

8条回答
  •  无人及你
    2020-11-29 20:56

    None of the answers that involve sysconf(...) or get_nprocs() are correct for honouring the number of processors restricted to a task by cpu affinity.

    You need something like this to get the number of processors available to a task:

    #define _GNU_SOURCE
    #include 
    #include 
    
    int nprocs()
    {
      cpu_set_t cs;
      CPU_ZERO(&cs);
      sched_getaffinity(0, sizeof(cs), &cs);
      return CPU_COUNT(&cs);
    }
    
    int main()
    {
      printf("procs=%d\n", nprocs());
      return 0;
    }
    

提交回复
热议问题