5

Is there a way to determine how many physical cores a target machine has at compile time in C/C++ in Linux under GCC?

I am aware of other methods like td::thread::hardware_concurrency() in C++11 or sysconf(_SC_NPROCESSORS_ONLN) but I am curious to know if there is actually a way to obtain this information at compile time.

Camilo Celis Guzman
  • 595
  • 1
  • 5
  • 17
  • 11
    Your program will become unportable if you determine this at compile time. – Henri Menke Jul 12 '17 at 03:11
  • 1
    You can use cmake to fill in a templated header that you include into your program that defines this: https://cmake.org/cmake/help/v3.0/module/ProcessorCount.html and https://cmake.org/cmake/help/v3.0/command/configure_file.html This works on any platform (that cmake supports) – xaxxon Jul 12 '17 at 03:15
  • 1
    Note that this only retrieves the core count of the PC that the compiler is running on. The compiled EXE can still be run on other PCs with different core counts. – Remy Lebeau Jul 12 '17 at 08:20
  • -DNCORES=8. How do you expect the compiler to know that on its own? – n. m. could be an AI Jan 17 '18 at 18:45
  • @Henri the program source won't necessarily become unportable (he could simply use a macro for example). And the program itself won't be any ore unportable than without it (ELF / PE executable). – Johannes Schaub - litb Nov 22 '18 at 18:14

1 Answers1

7

You can query information during the build processes and pass it into the program as a pre-processor definition.

Example

g++ main.cpp -D PROC_COUNT=$(grep -c ^processor /proc/cpuinfo)

where main.cpp is

#include <iostream>
int main() {
    std::cout << PROC_COUNT << std::endl;
    return 0;
}

Edit

As pointed out in the comments. If the target machine differs from the build machine then you'll need to replace the method grep -c ^processor /proc/cpuinfo with something that queries the number of processors on the target machine. The details would depend on what form of access you have to the target machine during build.

jodag
  • 19,885
  • 5
  • 47
  • 66
  • 2
    For the method of `PROC_COUNT` you can substitute in any method proposed here: https://stackoverflow.com/questions/6481005/how-to-obtain-the-number-of-cpus-cores-in-linux-from-the-command-line – Henri Menke Jul 12 '17 at 03:17
  • 4
    Note that this only retrieves the core count of the PC that the compiler is running on. The compiled EXE can still be run on other PCs with different core counts. – Remy Lebeau Jul 12 '17 at 08:19
  • That would be the build machine, not the target machine, but who cares... – n. m. could be an AI Jan 17 '18 at 18:47