7

On OS X, Is there a way to find out which CPU a thread is running on? An equivalent function for Linux is sched_getcpu

1
  • I need to know this as I'm trying to debug a performance problem with thread migration between cores - I want to log the CPU (core) affinity as the thread runs to see how often the thread gets migrated. Unfortunately there doesn't seem to be a standard way of doing this in BSD or OS X.
    – Paul R
    Apr 28, 2016 at 14:25

1 Answer 1

5

GetCurrentProcessorNumber example shows code that implements this functionality using the CPUID instruction. I have tried it myself and can confirm it works on Mac OS X.

Here is my version which I used on Mac OS X

#include <cpuid.h>

#define CPUID(INFO, LEAF, SUBLEAF) __cpuid_count(LEAF, SUBLEAF, INFO[0], INFO[1], INFO[2], INFO[3])

#define GETCPU(CPU) {                              \
        uint32_t CPUInfo[4];                           \
        CPUID(CPUInfo, 1, 0);                          \
        /* CPUInfo[1] is EBX, bits 24-31 are APIC ID */ \
        if ( (CPUInfo[3] & (1 << 9)) == 0) {           \
          CPU = -1;  /* no APIC on chip */             \
        }                                              \
        else {                                         \
          CPU = (unsigned)CPUInfo[1] >> 24;                    \
        }                                              \
        if (CPU < 0) CPU = 0;                          \
      }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.