阅读Darwin源码的时候看到这个方法,感觉挺有用处,且考虑了多种平台下的实现方式,直接贴代码,以后说不定会用到~
单一种平台下的实现方法可能很容易,但是把这些个系统都收集在一起,在一个函数中实现还是极好的
【转载请注明出处】:http://blog.csdn.net/longlong530
-
UInt32 OS::GetNumProcessors()
-
-
-
SYSTEM_INFO theSystemInfo;
-
::GetSystemInfo(&theSystemInfo);
-
-
return (UInt32)theSystemInfo.dwNumberOfProcessors;
-
-
-
#if (__MacOSX__ || __FreeBSD__)
-
-
size_t len = sizeof(numCPUs);
-
-
-
-
(void) ::sysctl(mib,2,&numCPUs,&len,NULL,0);
-
-
-
-
-
-
#if(__linux__ || __linuxppc__)
-
-
char cpuBuffer[8192] = "";
-
StrPtrLen cpuInfoBuf(cpuBuffer, sizeof(cpuBuffer));
-
FILE *cpuFile = ::fopen( "/proc/cpuinfo", "r" );
-
-
{ cpuInfoBuf.Len = ::fread(cpuInfoBuf.Ptr, sizeof(char), cpuInfoBuf.Len, cpuFile);
-
-
-
-
StringParser cpuInfoFileParser(&cpuInfoBuf);
-
-
-
-
-
while( cpuInfoFileParser.GetDataRemaining() != 0 )
-
-
cpuInfoFileParser.GetThruEOL(&line);
-
StringParser lineParser(&line);
-
lineParser.ConsumeWhitespace();
-
-
if (lineParser.GetDataRemaining() == 0)
-
-
-
lineParser.ConsumeUntilWhitespace(&word);
-
-
if ( word.Equal("processor") )
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
StrPtrLen line(linebuff, sizeof(linebuff));
-
-
-
FILE *p = ::popen("uname -X","r");
-
while((::fgets(linebuff, sizeof(linebuff -1), p)) > 0)
-
-
StringParser lineParser(&line);
-
lineParser.ConsumeWhitespace();
-
-
if (lineParser.GetDataRemaining() == 0)
-
-
-
lineParser.ConsumeUntilWhitespace(&word);
-
-
if ( word.Equal("NumCPU"))
-
-
lineParser.GetThru(NULL,‘=‘);
-
lineParser.ConsumeWhitespace();
-
lineParser.ConsumeUntilWhitespace(&word);
-
-
::sscanf(word.Ptr, "%"_U32BITARG_"", &numCPUs);
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
numCPUs = sysconf(_SC_NPROC_ONLN);
-
-
-
-
-
-
-
PS: 函数摘自Darwin源码:\StreamServer\CommonUtilitiesLib\OS.cpp
【Darwin学习笔记】之获取系统处理器数量的方法
原文:https://www.cnblogs.com/lidabo/p/9466897.html