做代码优化,发现代码中获取系统 CPU 核数是通过 system 调用命令得到的,想想最近被 system 支配的恐惧,果断改掉。
linux c 中获取 CPU 核数的函数原语有两个:
1 2 3 |
#include <sys/sysinfo.h> get_nprocs_conf(); get_nprocs(); |
第二个函数是返回当前可用的 CPU 数量,不可用的意思是 CPU HANG 住了。如果安装了 man page,可以直接在 man page 中找到用法。
1 2 3 4 5 6 7 8 9 10 11 |
#include <stdio.h> #include <sys/sysinfo.h> int main(int argc, char *argv[]) { printf("This system has %d processors configured and " "%d processors available.\n", get_nprocs_conf(), get_nprocs()); return 0; } |
评论