以编程方式查找机器上的内核数

Programmatically find the number of cores on a machine(以编程方式查找机器上的内核数)
本文介绍了以编程方式查找机器上的内核数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法以独立于平台的方式从 C/C++ 确定一台机器有多少个内核?如果不存在这样的东西,那么按平台(Windows/*nix/Mac)确定它怎么样?

Is there a way to determine how many cores a machine has from C/C++ in a platform-independent way? If no such thing exists, what about determining it per-platform (Windows/*nix/Mac)?

推荐答案

C++11

#include <thread>

//may return 0 when not able to detect
const auto processor_count = std::thread::hardware_concurrency();

参考:std::thread::hardware_concurrency

在 C++11 之前的 C++ 中,没有可移植的方式.相反,您需要使用以下一种或多种方法(由适当的 #ifdef 行保护):

In C++ prior to C++11, there's no portable way. Instead, you'll need to use one or more of the following methods (guarded by appropriate #ifdef lines):

  • Win32

SYSTEM_INFO sysinfo;
GetSystemInfo(&sysinfo);
int numCPU = sysinfo.dwNumberOfProcessors;

  • Linux、Solaris、AIX和MacOSX>=10.4(即Tiger以上)

    int numCPU = sysconf(_SC_NPROCESSORS_ONLN);
    

  • FreeBSD、MacOSX、NetBSD、OpenBSD等

    int mib[4];
    int numCPU;
    std::size_t len = sizeof(numCPU); 
    
    /* set the mib for hw.ncpu */
    mib[0] = CTL_HW;
    mib[1] = HW_AVAILCPU;  // alternatively, try HW_NCPU;
    
    /* get the number of CPUs from the system */
    sysctl(mib, 2, &numCPU, &len, NULL, 0);
    
    if (numCPU < 1) 
    {
        mib[1] = HW_NCPU;
        sysctl(mib, 2, &numCPU, &len, NULL, 0);
        if (numCPU < 1)
            numCPU = 1;
    }
    

  • HPUX

    int numCPU = mpctl(MPC_GETNUMSPUS, NULL, NULL);
    

  • IRIX

    int numCPU = sysconf(_SC_NPROC_ONLN);
    

  • Objective-C(MacOSX>=10.5或iOS)

    NSUInteger a = [[NSProcessInfo processInfo] processorCount];
    NSUInteger b = [[NSProcessInfo processInfo] activeProcessorCount];
    

  • 这篇关于以编程方式查找机器上的内核数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

    本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

    相关文档推荐

    Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
    How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
    OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
    How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
    What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
    Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)