零零乙 2008-09-29 11:51 采纳率: 33.3%
浏览 421
已采纳

编程查找机器上的核数

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)?

转载于:https://stackoverflow.com/questions/150355/programmatically-find-the-number-of-cores-on-a-machine

  • 写回答

20条回答 默认 最新

  • 零零乙 2008-09-29 14:14
    关注

    C++11

    1. //may return 0 when not able to detect
    2. unsigned concurentThreadsSupported = std::thread::hardware_concurrency();

    Reference: std::thread::hardware_concurrency


    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

      1. SYSTEM_INFO sysinfo;
      2. GetSystemInfo(&sysinfo);
      3. int numCPU = sysinfo.dwNumberOfProcessors;
    • Linux, Solaris, AIX and Mac OS X >=10.4 (i.e. Tiger onwards)

      int numCPU = sysconf(_SC_NPROCESSORS_ONLN);
      
    • FreeBSD, MacOS X, NetBSD, OpenBSD, etc.

      1. int mib[4];
      2. int numCPU;
      3. std::size_t len = sizeof(numCPU);
      4. /* set the mib for hw.ncpu */
      5. mib[0] = CTL_HW;
      6. mib[1] = HW_AVAILCPU; // alternatively, try HW_NCPU;
      7. /* get the number of CPUs from the system */
      8. sysctl(mib, 2, &numCPU, &len, NULL, 0);
      9. if (numCPU < 1)
      10. {
      11. mib[1] = HW_NCPU;
      12. sysctl(mib, 2, &numCPU, &len, NULL, 0);
      13. if (numCPU < 1)
      14. numCPU = 1;
      15. }
    • HPUX

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

      int numCPU = sysconf(_SC_NPROC_ONLN);
      
    • Objective-C (Mac OS X >=10.5 or iOS)

      1. NSUInteger a = [[NSProcessInfo processInfo] processorCount];
      2. NSUInteger b = [[NSProcessInfo processInfo] activeProcessorCount];

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(19条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部