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.

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


BUILD_COMMAND make -j${Ncpu}