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

问题描述 投票:0回答:3

我知道如何获取C中的逻辑核心数。

sysconf(_SC_NPROCESSORS_CONF);

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

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

c linux cpu
3个回答
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;
}

这是一个使用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;
}

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

No. of Physical Core(s) : 4
No. of Logical Core(s) : 4

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

No. of Physical Core(s) : 2
No. of Logical Core(s) : 4

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


1
投票

您可能只是读取并解析/proc/cpuinfo伪文件(有关详细信息,请参阅proc(5);将该伪文件作为文本文件打开并逐行读取;在终端中尝试cat /proc/cpuinfo)。

优点是你只是在解析一个(特定于Linux的)文本[伪]文件(不需要任何外部库,比如在Gengisdave's answer中),缺点是你需要解析它(不是很大,读取80字节)在循环中使用fgets的行然后使用sscanf并测试扫描的项目数....)

htflags:线上的存在意味着你的CPU有hyper-threading。 CPU线程数由processor:行数给出。物理核心的实际数量由cpu cores:给出(所有这些都在我的机器上使用4.1内核)。

我不确定你是否正确想要了解你有多少物理核心。超线程实际上可能很有用。你需要基准测试。

您可能应该使应用程序中的工作线程数(例如,线程池的大小)可由用户配置。即使在4核超线程处理器上,我也可能希望不超过3个正在运行的线程(因为我想将其他线程用于其他东西)。


1
投票

没有任何lib:

int main()
{
unsigned int eax=11,ebx=0,ecx=1,edx=0;

asm volatile("cpuid"
        : "=a" (eax),
          "=b" (ebx),
          "=c" (ecx),
          "=d" (edx)
        : "0" (eax), "2" (ecx)
        : );

printf("Cores: %d\nThreads: %d\nActual thread: %d\n",eax,ebx,edx);
}

输出:

Cores: 4
Threads: 8
Actual thread: 1
© www.soinside.com 2019 - 2024. All rights reserved.