How to set thread affinity to either performance or efficient cores?

345 Views Asked by At

I am familiar with using pthread_attr_setaffinity_np to set the cpu that a thread would like to run on. In the code below, thread t requests to execute on cpu_target (set to 13), by setting the affinity mask of cpuset via the CPU_SET macro.

#include <pthread.h>
#include <sys/sysinfo.h>

int main(int argc, char *argv[])
{
  pthread_attr_t attr;
  pthread_t t;
  cpu_set_t cpuset;
  const int cpu_target = 13;
  if (cpu_target >= get_nprocs_conf())
    return -1;

  CPU_ZERO(&cpuset);
  CPU_SET(cpu_target, &cpuset);
  pthread_attr_init(&attr);
  pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), &cpuset);
  pthread_create(&t, &attr, [](void*) -> void* { return nullptr; }, nullptr);

  pthread_join(t, nullptr);
  pthread_attr_destroy(&attr);

  return 0;
}

We can enquire as to how many cores are available. If there are N cores available, we can set the affinity mask of each thread to run on a core from 0 to N-1.

Many processors now have performance and efficient cores. For example, the i9-14900K has 24 cores (8 performance and 16 efficient Cores); with the 8 performance cores each able to run 2 hyperthreads.

How can I configure thread affinity for either a performance core; or an efficiency core?

1

There are 1 best solutions below

1
On

How can I configure thread affinity for either a performance core; or an efficiency core?

There is no standard interface defined by C, C++, or POSIX for distinguishing among execution units with different characteristics. In fact, pthread_attr_setaffinity_np() itself is a non-standard GNU extension.* Other environments may provide similar interfaces, but at the level of generality of the question -- that is, without specifying a particular environment -- the main answer is that there is no standard way to control on which execution units your programs run.

A secondary answer is that for the most part, you shouldn't need to do. A key enabling technology for the kind of CPU design you're talking about is built-in logic for automatically making good choices about on which cores any given thread should run. Looking forward, it's also reasonable to expect that compilers will soon get better at generating code that helps such CPUs do a good job of that, and that operating system kernels will soon learn how to use such CPUs to the best advantage. Only if you have very special needs might it make sense to invest time and money into the kind of manual core-affinity management you describe.

But if you do have such needs, and if we can safely conclude from your Glibc dependency that you're looking for a Linux-specific solution, then that would probably be to parse /proc/cpuinfo to determine the characteristics of the system's CPU cores. Then use that information to choose which cores to set affinity for.


* The same for related function sched_setaffinity().