Hard
Comparing rdtsc readings taken on different cores
A latency-measurement library takes a raw rdtsc reading on thread A (pinned to core 3) at the start of an operation, and later compares it against a raw rdtsc reading taken by thread B (pinned to core 7) that completes the operation, computing elapsed cycles as a plain subtraction, with no clock_gettime() and no syscall, just the rdtsc instruction on each side. On a typical modern x86-64 server CPU, is this safe, and why would anyone reach for raw rdtsc over clock_gettime()/gettimeofday() in the first place?
latency.cpp
#include <x86intrin.h>
#include <cstdint>
// Hot-path timestamp: a single instruction, no syscall.
inline uint64_t rdtsc_now() {
return __rdtsc();
}
// thread A (core 3):
uint64_t start = rdtsc_now();
// ... send the order ...
// thread B (core 7), later:
uint64_t end = rdtsc_now();
uint64_t elapsed_cycles = end - start; // cross-core comparison39 of 53 in Operating Systems