如何使用c编程获取linux上的内核数量?

Bha*_*ain 0 c linux cpu

我知道如何在C中获取逻辑核心的数量.

sysconf(_SC_NPROCESSORS_CONF);
Run Code Online (Sandbox Code Playgroud)

这将在我的i3处理器上返回4.但实际上i3中只有2个核心.

我怎样才能获得物理核心数?

gen*_*ave 5

这是使用libcpuid的C解决方案.

cores.c:

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

int main(void)
{
    struct cpu_raw_data_t raw;
    struct cpu_id_t data;

    cpuid_get_raw_data(&raw);
    cpu_identify(&raw, &data);
    printf("No. of Physical Core(s) : %d\n", data.num_cores);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是一个使用Boost的C++解决方案.

cores.cpp:

// use boost to get number of cores on the processor
// compile with : g++ -o cores cores.cpp -lboost_system -lboost_thread

#include <iostream>
#include <boost/thread.hpp>

int main ()
{
    std::cout << "No. of Physical Core(s) : " << boost::thread::physical_concurrency() << std::endl;
    std::cout << "No. of Logical Core(s) : " << boost::thread::hardware_concurrency() << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在我的桌面(i5 2310)上它返回:

No. of Physical Core(s) : 4
No. of Logical Core(s) : 4
Run Code Online (Sandbox Code Playgroud)

在我的笔记本电脑上(i5 480M):

No. of Physical Core(s) : 2
No. of Logical Core(s) : 4
Run Code Online (Sandbox Code Playgroud)

这意味着我的笔记本电脑处理器具有超线程技术