Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sched_getcpu() equivalent for OS X?

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

like image 428
Will Avatar asked Nov 16 '15 21:11

Will


1 Answers

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;                          \
      }
like image 142
Peter Skarpetis Avatar answered Sep 21 '22 12:09

Peter Skarpetis