如何检索C / Linux上的处理器数量?

我正在编写一个小型C应用程序,它使用一些线程来处理数据。 我希望能够知道某台机器上的处理器数量,而不使用system()和小脚本。

我能想到的唯一方法是解析/ proc / cpuinfo 。 任何其他有用的建议?

正如其他人在评论中提到的, 这个答案很有用:

 numCPU = sysconf( _SC_NPROCESSORS_ONLN ); 

留下可能会跳过评论的人们的解决方案……

为什么不使用sys / sysinfo.h?

 #include  #include  void main () { printf ("You have %d processors.\n", get_nprocs ()); } 

可以在手册页上找到更多信息

 $ man 3 get_nprocs 
 machine:/sys/devices/system/cpu$ ls cpu0 cpu3 cpu6 kernel_max perf_counters sched_mc_power_savings cpu1 cpu4 cpu7 offline possible cpu2 cpu5 cpuidle online present 

如果你有一台带有sysfs的机器,请查看/ sys / devices / system / cpu。

确保你问的是你想要的东西 – CPU,内核,超线程等。

以下是我用来计算内核数量的代码…..它可能对你有所帮助

 //Finding the number of cores(logical processor) using cpuid instruction..... __asm { mov eax,01h //01h is for getting number of cores present in the processor cpuid mov t,ebx } 

(t >> 16)&0xff包含数字核心……..

我想这可以帮到你http://lists.gnu.org/archive/html/autoconf/2002-08/msg00126.html

 #include  void getPSN(char *PSN) {int varEAX, varEBX, varECX, varEDX; char str[9]; //%eax=1 gives most significant 32 bits in eax __asm__ __volatile__ ("cpuid": "=a" (varEAX), "=b" (varEBX), "=c" (varECX), "=d" (varEDX) : "a" (1)); sprintf(str, "%08X", varEAX); //ie XXXX-XXXX-xxxx-xxxx-xxxx-xxxx sprintf(PSN, "%C%C%C%C-%C%C%C%C", str[0], str[1], str[2], str[3], str[4], str[5], str[6], str[7]); //%eax=3 gives least significant 64 bits in edx and ecx [if PN is enabled] __asm__ __volatile__ ("cpuid": "=a" (varEAX), "=b" (varEBX), "=c" (varECX), "=d" (varEDX) : "a" (3)); sprintf(str, "%08X", varEDX); //ie xxxx-xxxx-XXXX-XXXX-xxxx-xxxx sprintf(PSN, "%s-%C%C%C%C-%C%C%C%C", PSN, str[0], str[1], str[2], str[3], str[4], str[5], str[6], str[7]); sprintf(str, "%08X", varECX); //ie xxxx-xxxx-xxxx-xxxx-XXXX-XXXX sprintf(PSN, "%s-%C%C%C%C-%C%C%C%C", PSN, str[0], str[1], str[2], str[3], str[4], str[5], str[6], str[7]); } int main() { char PSN[30]; //24 Hex digits, 5 '-' separators, and a '\0' getPSN(PSN); printf("%s\n", PSN); //compare with: lshw | grep serial: return 0; }