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

后端 未结 8 1690
情歌与酒
情歌与酒 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:52

    Personally for recent intel cpus I use this:

    int main()
    {
    unsigned int eax=11,ebx=0,ecx=1,edx=0;
    
    asm volatile("cpuid"
            : "=a" (eax),
              "=b" (ebx),
              "=c" (ecx),
              "=d" (edx)
            : "0" (eax), "2" (ecx)
            : );
    
    printf("Cores: %d\nThreads: %d\nActual thread: %d\n",eax,ebx,edx);
    }
    

    Output:

    Cores: 4
    Threads: 8
    Actual thread: 1
    

    Or, more concisely:

    #include 
    
    int main()
    {
    unsigned int ncores=0,nthreads=0,ht=0;
    
    asm volatile("cpuid": "=a" (ncores), "=b" (nthreads) : "a" (0xb), "c" (0x1) : );
    
    ht=(ncores!=nthreads);
    
    printf("Cores: %d\nThreads: %d\nHyperThreading: %s\n",ncores,nthreads,ht?"Yes":"No");
    
    return 0;
    }
    

    Output:

    Cores: 4
    Threads: 8
    HyperThreading: Yes
    

提交回复
热议问题