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

Will
  • 71
  • 2
  • 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 '16 at 14:25

1 Answers1

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;                          \
      }
Community
  • 1
  • 1
Peter Skarpetis
  • 543
  • 3
  • 11