GetCycleCount guarantees to return synchronous values on different cores and provide constant rate only on modern Intel and AMD processors NOTE: rdtscp is used to prevent out of order execution rdtsc can be reordered, while rdtscp cannot be reordered with preceding instructions PERFORMANCE: rdtsc - 15 cycles per call , rdtscp - 19 cycles per call WARNING: following instruction can be executed out-
| 48 | // PERFORMANCE: rdtsc - 15 cycles per call , rdtscp - 19 cycles per call |
| 49 | // WARNING: following instruction can be executed out-of-order |
| 50 | Y_FORCE_INLINE ui64 GetCycleCount() noexcept { |
| 51 | #if defined(_MSC_VER) |
| 52 | // Generates the rdtscp instruction, which returns the processor time stamp. |
| 53 | // The processor time stamp records the number of clock cycles since the last reset. |
| 54 | static const bool haveRdtscp = ::NPrivate::HaveRdtscpImpl(); |
| 55 | |
| 56 | if (haveRdtscp) { |
| 57 | unsigned int aux; |
| 58 | return __rdtscp(&aux); |
| 59 | } else { |
| 60 | return __rdtsc(); |
| 61 | } |
| 62 | #elif defined(_x86_64_) |
| 63 | static const bool haveRdtscp = ::NPrivate::HaveRdtscpImpl(); |
| 64 | |
| 65 | unsigned hi, lo; |
| 66 | |
| 67 | if (haveRdtscp) { |
| 68 | __asm__ __volatile__("rdtscp" |
| 69 | : "=a"(lo), "=d"(hi)::"%rcx"); |
| 70 | } else { |
| 71 | __asm__ __volatile__("rdtsc" |
| 72 | : "=a"(lo), "=d"(hi)); |
| 73 | } |
| 74 | |
| 75 | return ((unsigned long long)lo) | (((unsigned long long)hi) << 32); |
| 76 | #elif defined(_i386_) |
| 77 | static const bool haveRdtscp = ::NPrivate::HaveRdtscpImpl(); |
| 78 | |
| 79 | ui64 x; |
| 80 | if (haveRdtscp) { |
| 81 | __asm__ volatile("rdtscp\n\t" |
| 82 | : "=A"(x)::"%ecx"); |
| 83 | } else { |
| 84 | __asm__ volatile("rdtsc\n\t" |
| 85 | : "=A"(x)); |
| 86 | } |
| 87 | return x; |
| 88 | #elif defined(_darwin_) |
| 89 | return mach_absolute_time(); |
| 90 | #elif defined(__clang__) && !defined(_arm_) |
| 91 | return __builtin_readcyclecounter(); |
| 92 | #elif defined(_arm32_) |
| 93 | return MicroSeconds(); |
| 94 | #elif defined(_arm64_) |
| 95 | ui64 x; |
| 96 | |
| 97 | __asm__ __volatile__("isb; mrs %0, cntvct_el0" |
| 98 | : "=r"(x)); |
| 99 | |
| 100 | return x; |
| 101 | #else |
| 102 | #error "unsupported arch" |
| 103 | #endif |
| 104 | } |