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. When building a non-CMake ExternalProject from CMake by default the external project will build serially, which can be very slow. This is because CMake doesn’t have a way to know if the non-CMake ExternalProject is capable of being built in parallel. When it’s known that the 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.

There are two methods to get CPU count in CMake.

An example is on ARM systems such as Raspberry Pi 4, with four CPU cores:

  • ProcessorCount: 4
  • cmake_host_system_information(RESULT … QUERY NUMBER_OF_PHYSICAL_CORES): 1

One could make a function that first tries cmake_host_system_information and then ProcessorCount, but usually we just use cmake_host_system_information alone.

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