Programmatically find the number of cores on a machine

前端 未结 19 2139
刺人心
刺人心 2020-11-22 16:38

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/*

相关标签:
19条回答
  • 2020-11-22 17:22

    This functionality is part of the C++11 standard.

    #include <thread>
    
    unsigned int nthreads = std::thread::hardware_concurrency();
    

    For older compilers, you can use the Boost.Thread library.

    #include <boost/thread.hpp>
    
    unsigned int nthreads = boost::thread::hardware_concurrency();
    

    In either case, hardware_concurrency() returns the number of threads that the hardware is capable of executing concurrently based on the number of CPU cores and hyper-threading units.

    0 讨论(0)
  • 2020-11-22 17:23

    More on OS X: sysconf(_SC_NPROCESSORS_ONLN) is available only versions >= 10.5, not 10.4.

    An alternative is the HW_AVAILCPU/sysctl() BSD code which is available on versions >= 10.2.

    0 讨论(0)
  • 2020-11-22 17:24

    OS X alternative: The solution described earlier based on [[NSProcessInfo processInfo] processorCount] is only available on OS X 10.5.0, according to the docs. For earlier versions of OS X, use the Carbon function MPProcessors().

    If you're a Cocoa programmer, don't be freaked out by the fact that this is Carbon. You just need to need to add the Carbon framework to your Xcode project and MPProcessors() will be available.

    0 讨论(0)
  • 2020-11-22 17:25

    One more Windows recipe: use system-wide environment variable NUMBER_OF_PROCESSORS:

    printf("%d\n", atoi(getenv("NUMBER_OF_PROCESSORS")));
    
    0 讨论(0)
  • 2020-11-22 17:26

    On Linux, you can read the /proc/cpuinfo file and count the cores.

    0 讨论(0)
  • 2020-11-22 17:28

    you can use WMI in .net too but you're then dependent on the wmi service running etc. Sometimes it works locally, but then fail when the same code is run on servers. I believe that's a namespace issue, related to the "names" whose values you're reading.

    0 讨论(0)
提交回复
热议问题