ProcessorCount.cmake 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # - ProcessorCount(var)
  2. # Determine the number of processors/cores and save value in ${var}
  3. #
  4. # Sets the variable named ${var} to the number of physical cores available on
  5. # the machine if the information can be determined. Otherwise it is set to 0.
  6. # Currently this functionality is only implemented for Windows, Mac OS X and
  7. # Unix systems providing getconf or the /proc/cpuinfo interface (e.g. Linux).
  8. # A more reliable way might be to compile a small C program that uses the CPUID
  9. # instruction, but that again requires compiler support or compiling assembler
  10. # code.
  11. #=============================================================================
  12. # Copyright 2010 Kitware, Inc.
  13. #
  14. # Distributed under the OSI-approved BSD License (the "License");
  15. # see accompanying file Copyright.txt for details.
  16. #
  17. # This software is distributed WITHOUT ANY WARRANTY; without even the
  18. # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  19. # See the License for more information.
  20. #=============================================================================
  21. # (To distribute this file outside of CMake, substitute the full
  22. # License text for the above reference.)
  23. function(ProcessorCount var)
  24. # Unknown:
  25. set(count 0)
  26. if(WIN32)
  27. # Windows:
  28. set(count "$ENV{NUMBER_OF_PROCESSORS}")
  29. message("ProcessorCount: using environment variable")
  30. elseif(APPLE)
  31. # Mac:
  32. find_program(ProcessorCount_cmd_sysctl sysctl
  33. PATHS /usr/sbin)
  34. if(ProcessorCount_cmd_sysctl)
  35. execute_process(COMMAND ${ProcessorCount_cmd_sysctl} -n hw.ncpu
  36. OUTPUT_STRIP_TRAILING_WHITESPACE
  37. OUTPUT_VARIABLE count)
  38. message("ProcessorCount: using sysctl '${ProcessorCount_cmd_sysctl}'")
  39. endif()
  40. else()
  41. # Linux (and other systems with getconf):
  42. find_program(ProcessorCount_cmd_getconf getconf)
  43. if(ProcessorCount_cmd_getconf)
  44. execute_process(COMMAND ${ProcessorCount_cmd_getconf} _NPROCESSORS_ONLN
  45. OUTPUT_STRIP_TRAILING_WHITESPACE
  46. OUTPUT_VARIABLE count)
  47. message("ProcessorCount: using getconf '${ProcessorCount_cmd_getconf}'")
  48. endif()
  49. endif()
  50. # Execute this code when there is no 'sysctl' or 'getconf' or
  51. # when previously executed methods return empty output:
  52. #
  53. if(NOT count)
  54. # Systems with /proc/cpuinfo:
  55. set(cpuinfo_file /proc/cpuinfo)
  56. if(EXISTS "${cpuinfo_file}")
  57. file(STRINGS "${cpuinfo_file}" procs REGEX "^processor.: [0-9]+$")
  58. list(LENGTH procs count)
  59. message("ProcessorCount: using cpuinfo '${cpuinfo_file}'")
  60. endif()
  61. endif()
  62. set(${var} ${count} PARENT_SCOPE)
  63. endfunction()