Programmatically find the number of cores on a machine

前端 未结 19 2472
刺人心
刺人心 2020-11-22 16:38

Is there a way to determine how many cores a machine has from C/C++ in a platform-independent way? If no such thing exists, what about determining it per-platform (Windows/*

19条回答
  •  广开言路
    2020-11-22 17:16

    On Linux, it's may not be safe to to use _SC_NPROCESSORS_ONLN as it's not part of POSIX standard and the sysconf manual states as much. So there's a possibility that _SC_NPROCESSORS_ONLN may not be present:

     These values also exist, but may not be standard.
    
         [...]     
    
         - _SC_NPROCESSORS_CONF
                  The number of processors configured.   
         - _SC_NPROCESSORS_ONLN
                  The number of processors currently online (available).
    

    A simple approach would be to read /proc/stat or /proc/cpuinfo and count them:

    #include
    #include
    
    int main(void)
    {
    char str[256];
    int procCount = -1; // to offset for the first entry
    FILE *fp;
    
    if( (fp = fopen("/proc/stat", "r")) )
    {
      while(fgets(str, sizeof str, fp))
      if( !memcmp(str, "cpu", 3) ) procCount++;
    }
    
    if ( procCount == -1) 
    { 
    printf("Unable to get proc count. Defaulting to 2");
    procCount=2;
    }
    
    printf("Proc Count:%d\n", procCount);
    return 0;
    }
    

    Using /proc/cpuinfo:

    #include
    #include
    
    int main(void)
    {
    char str[256];
    int procCount = 0;
    FILE *fp;
    
    if( (fp = fopen("/proc/cpuinfo", "r")) )
    {
      while(fgets(str, sizeof str, fp))
      if( !memcmp(str, "processor", 9) ) procCount++;
    }
    
    if ( !procCount ) 
    { 
    printf("Unable to get proc count. Defaulting to 2");
    procCount=2;
    }
    
    printf("Proc Count:%d\n", procCount);
    return 0;
    }
    

    The same approach in shell using grep:

    grep -c ^processor /proc/cpuinfo
    

    Or

    grep -c ^cpu /proc/stat # subtract 1 from the result
    

提交回复
热议问题