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

后端 未结 8 1653
情歌与酒
情歌与酒 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 21:05

    This code (drawn from here) should work on both windows and *NIX platforms.

    #ifdef _WIN32
    #define WIN32_LEAN_AND_MEAN
    #include <windows.h>
    #else
    #include <unistd.h>
    #endif
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <errno.h>
    
    
    int main() {
      long nprocs = -1;
      long nprocs_max = -1;
    #ifdef _WIN32
    #ifndef _SC_NPROCESSORS_ONLN
    SYSTEM_INFO info;
    GetSystemInfo(&info);
    #define sysconf(a) info.dwNumberOfProcessors
    #define _SC_NPROCESSORS_ONLN
    #endif
    #endif
    #ifdef _SC_NPROCESSORS_ONLN
      nprocs = sysconf(_SC_NPROCESSORS_ONLN);
      if (nprocs < 1)
      {
        fprintf(stderr, "Could not determine number of CPUs online:\n%s\n", 
    strerror (errno));
        exit (EXIT_FAILURE);
      }
      nprocs_max = sysconf(_SC_NPROCESSORS_CONF);
      if (nprocs_max < 1)
      {
        fprintf(stderr, "Could not determine number of CPUs configured:\n%s\n", 
    strerror (errno));
        exit (EXIT_FAILURE);
      }
      printf ("%ld of %ld processors online\n",nprocs, nprocs_max);
      exit (EXIT_SUCCESS);
    #else
      fprintf(stderr, "Could not determine number of CPUs");
      exit (EXIT_FAILURE);
    #endif
    }
    
    0 讨论(0)
  • 2020-11-29 21:07
    #include <unistd.h>
    long number_of_processors = sysconf(_SC_NPROCESSORS_ONLN);
    
    0 讨论(0)
提交回复
热议问题