#ifdef __x86_64__
#include "Perf.h"
#include "llvm/Support/Error.h"
#include "gtest/gtest.h"
#include <chrono>
#include <cstdint>
using namespace lldb_private;
using namespace process_linux;
using namespace llvm;
static Expected<uint64_t> readTsc() {
unsigned int eax, ebx, ecx, edx;
__asm__ __volatile__("cpuid"
: "=a"(eax), "=b"(ebx), "=c"(ecx), "=d"(edx)
: "0"(0x80000001));
if (!(edx & (1u << 27))) {
return createStringError(inconvertibleErrorCode(),
"Missing rdtscp support.");
}
unsigned cpu;
unsigned long rax, rdx;
__asm__ __volatile__("rdtscp\n" : "=a"(rax), "=d"(rdx), "=c"(cpu)::);
return (rdx << 32) + rax;
}
TEST(Perf, TscConversion) {
const int SLEEP_SECS = 1;
std::chrono::nanoseconds SLEEP_NANOS{std::chrono::seconds(SLEEP_SECS)};
Expected<LinuxPerfZeroTscConversion> params =
LoadPerfTscConversionParameters();
if (!params)
GTEST_SKIP() << toString(params.takeError());
Expected<uint64_t> tsc_before_sleep = readTsc();
sleep(SLEEP_SECS);
Expected<uint64_t> tsc_after_sleep = readTsc();
if (!tsc_before_sleep)
GTEST_SKIP() << toString(tsc_before_sleep.takeError());
if (!tsc_after_sleep)
GTEST_SKIP() << toString(tsc_after_sleep.takeError());
uint64_t converted_tsc_diff =
params->ToNanos(*tsc_after_sleep) - params->ToNanos(*tsc_before_sleep);
std::chrono::microseconds acceptable_overhead(500);
ASSERT_GE(converted_tsc_diff, static_cast<uint64_t>(SLEEP_NANOS.count()));
ASSERT_LT(converted_tsc_diff,
static_cast<uint64_t>((SLEEP_NANOS + acceptable_overhead).count()));
}
#endif