Last active
January 24, 2018 22:39
-
-
Save daverigby/d00b9648401930e6dbc9d6bfdb456afa to your computer and use it in GitHub Desktop.
get current core number on macOS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <atomic> | |
| #if defined(__i386__) || defined(__x86_64__) | |
| #include <cpuid.h> | |
| #endif | |
| #include <cstdio> | |
| #include <chrono> | |
| #include <cinttypes> | |
| static inline uint64_t rdtscp( uint32_t & aux ) | |
| { | |
| uint64_t rax,rdx; | |
| asm volatile ( "rdtscp\n" : "=a" (rax), "=d" (rdx), "=c" (aux) : : ); | |
| return (rdx << 32) + rax; | |
| } | |
| int PhysicalCoreID() { | |
| // clang/gcc both provide cpuid.h, which defines __get_cpuid(), for x86_64 and i386. | |
| unsigned eax, ebx = 0, ecx, edx; | |
| if (!__get_cpuid(1, &eax, &ebx, &ecx, &edx)) { | |
| return -1; | |
| } | |
| return ebx >> 24; | |
| } | |
| __attribute__((always_inline)) | |
| static __inline__ unsigned int | |
| _os_cpu_number(void) | |
| { | |
| #if defined(__arm__) && defined(_ARM_ARCH_6) | |
| uintptr_t p; | |
| __asm__("mrcp15, 0, %[p], c13, c0, 3" : [p] "=&r" (p)); | |
| return (unsigned int)(p & 0x3ul); | |
| #elif defined(__arm64__) | |
| uint64_t p; | |
| __asm__("mrs%[p], TPIDRRO_EL0" : [p] "=&r" (p)); | |
| return (unsigned int)p & 0x7; | |
| #elif defined(__x86_64__) || defined(__i386__) | |
| struct { uintptr_t p1, p2; } p; | |
| __asm__("sidt %[p]" : [p] "=&m" (p)); | |
| return (unsigned int)(p.p1 & 0xfff); | |
| #else | |
| #error _os_cpu_number not implemented on this architecture | |
| #endif | |
| } | |
| int main() { | |
| while (true) { | |
| std::atomic<uint32_t> aux; | |
| //rdtscp(aux); | |
| auto start = std::chrono::steady_clock::now(); | |
| // aux = _os_cpu_number(); | |
| aux = PhysicalCoreID(); | |
| auto end = std::chrono::steady_clock::now(); | |
| fprintf(stderr, "%d - %d\n", aux.load(), std::chrono::duration_cast<std::chrono::nanoseconds>(end-start).count()); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment