How to get CPU info in C on Linux, such as number

2020-02-08 18:40发布

Is it possible to get such info by some API or function, rather than parsing the /proc/cpuinfo?

9条回答
\"骚年 ilove
2楼-- · 2020-02-08 18:48

You can use this for mostly all kind of linux distro

For C code

 num_cpus = sysconf( _SC_NPROCESSORS_ONLN );

(In QNX systems , you can use num_cpus = sysinfo_numcpu())

For shell scripting, you can use cat /proc/cpuinfo

or use lscpu or nproc commands in linux

查看更多
We Are One
3楼-- · 2020-02-08 18:50

No, it is not. Either you must parse cpuinfo file, or some library will do it for you.

查看更多
我只想做你的唯一
4楼-- · 2020-02-08 18:51

Parse the file /proc/cpuinfo. This'll give you lot of details about the CPU. Extract the relevant fields into your C/C++ file.

查看更多
Animai°情兽
5楼-- · 2020-02-08 18:52

libcpuid provides a simple API which will directly return all the CPU features, including number of cores. To get the number of cores at runtime, you could do something like this:

#include <stdio.h>
#include <libcpuid.h>

int main(void)
{
    if (!cpuid_present()) {
        printf("Sorry, your CPU doesn't support CPUID!\n");
        return -1;
    }

    struct cpu_raw_data_t raw; 
    struct cpu_id_t data;     

    if (cpuid_get_raw_data(&raw) < 0) { 
        printf("Sorry, cannot get the CPUID raw data.\n");
        printf("Error: %s\n", cpuid_error());
        return -2;
    }

    if (cpu_identify(&raw, &data) < 0) {    
        printf("Sorrry, CPU identification failed.\n");
        printf("Error: %s\n", cpuid_error());
        return -3;
    }

    printf("Processor has %d physical cores\n", data.num_cores);
    return 0;
}
查看更多
家丑人穷心不美
6楼-- · 2020-02-08 19:04

Depending on your flavor of Linux you will get different results from /proc/cpuid.

This works for me on CentOS for getting total number of cores.

cat /proc/cpuinfo | grep -w cores | sed -e 's/\t//g' | awk '{print $3}' | xargs | sed -e 's/\ /+/g' | bc

The same doesn't work in Ubuntu. For Ubuntu you can use the following command.

nproc
查看更多
爷的心禁止访问
7楼-- · 2020-02-08 19:06

Have you ever seen the output of this shell command "cat /proc/cpuinfo"? I think there you can get out all the information that you need. To read the information in a C program I would prefer the file manipulation functions like fopen, fgets and so on.

查看更多
登录 后发表回答