CMake get CPU count
For moderately advanced tasks in CMake it can be useful to get the CPU count to allow building or testing in parallel with non-CMake-based
ExternalProject.
Building a non-CMake ExternalProject from CMake with GNU Make by default builds serially, which can be very slow.
This is because CMake doesn’t know if the non-CMake ExternalProject is capable of being built in parallel.
When it’s known that the non-CMake-based ExternalProject can be built in parallel, it’s necessary to get the CPU count in CMake as simply putting make -j
can
overwhelm the computer.
Get CPU count in CMake via cmake_host_system_information. cmake_host_system_information should be used instead of ProcessorCount. The CMake module script ProcessorCount is known to be not as accurate as the C++-based cmake_host_system_information.
Example: specify the parameters relevant to CPU count:
cmake_host_system_information(RESULT Ncpu QUERY NUMBER_OF_PHYSICAL_CORES)
message(STATUS "CMake ${CMAKE_VERSION} using ${Ncpu} threads")
include(ExternalProject)
ExternalProject_Add(demo
BUILD_COMMAND make -j${Ncpu}
)