1. 程式人生 > 實用技巧 >C獲取系統中CPU核數

C獲取系統中CPU核數

1、在Linux下獲取CPU核數
linux下可以通過linux系統提供的sysconf()來獲取當前CPU個數,sysconf在標頭檔案unistd.h中宣告。
sysconf函式中輸入引數_SC_NPROCESSORS_CONF和_SC_NPROCESSORS_ONLN均可以獲取系統CPU個數。
_SC_NPROCESSORS_CONF:返回系統所有的CPU核數,這個值也包括系統中禁止使用者使用的CPU個數;
_SC_NPROCESSORS_ONLN:返回系統中可用的CPU核數;
#include "unistd.h"
printf("system cpu num is %d\n", sysconf( _SC_NPROCESSORS_CONF));
printf(
"system enable cpu num is %d\n", sysconf(_SC_NPROCESSORS_ONLN));

2、GNU C Library也提供了一種獲取CPU個數的方法,get_nprocs_conf()和get_nprocs()函式可以用來獲取系統CPU個數,在標頭檔案“sys/sysinfo.h”中宣告。
get_nprocs_conf():與sysconf( _SC_NPROCESSORS_CONF)作用相同,獲取當前系統所有的CPU核數;
get_nprocs():與sysconf( _SC_NPROCESSORS_ONLN)作用相同,獲取當前系統使用者可以使用的CPU核數。

#include "sys/sysinfo.h"
printf("system cpu num is %d\n", get_nprocs_conf());
printf("system enable num is %d\n", get_nprocs());