1 //===-- PerfTests.cpp -----------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "Perf.h" 10 11 #include "llvm/Support/Error.h" 12 13 #include "gtest/gtest.h" 14 #include <chrono> 15 #include <cstdint> 16 17 using namespace lldb_private; 18 using namespace process_linux; 19 using namespace llvm; 20 21 /// Helper function to read current TSC value. 22 /// 23 /// This code is based on llvm/xray. 24 static Expected<uint64_t> readTsc() { 25 26 unsigned int eax, ebx, ecx, edx; 27 28 // We check whether rdtscp support is enabled. According to the x86_64 manual, 29 // level should be set at 0x80000001, and we should have a look at bit 27 in 30 // EDX. That's 0x8000000 (or 1u << 27). 31 __asm__ __volatile__("cpuid" 32 : "=a"(eax), "=b"(ebx), "=c"(ecx), "=d"(edx) 33 : "0"(0x80000001)); 34 if (!(edx & (1u << 27))) { 35 return createStringError(inconvertibleErrorCode(), 36 "Missing rdtscp support."); 37 } 38 39 unsigned cpu; 40 unsigned long rax, rdx; 41 42 __asm__ __volatile__("rdtscp\n" : "=a"(rax), "=d"(rdx), "=c"(cpu)::); 43 44 return (rdx << 32) + rax; 45 } 46 47 // Test TSC to walltime conversion based on perf conversion values. 48 TEST(Perf, TscConversion) { 49 // This test works by first reading the TSC value directly before 50 // and after sleeping, then converting these values to nanoseconds, and 51 // finally ensuring the difference is approximately equal to the sleep time. 52 // 53 // There will be slight overhead associated with the sleep call, so it isn't 54 // reasonable to expect the difference to be exactly equal to the sleep time. 55 56 const int SLEEP_SECS = 1; 57 std::chrono::nanoseconds SLEEP_NANOS{std::chrono::seconds(SLEEP_SECS)}; 58 59 Expected<PerfTscConversionParameters> params = 60 FetchPerfTscConversionParameters(); 61 62 // Skip the test if the conversion parameters aren't available. 63 if (!params) 64 GTEST_SKIP() << params.takeError(); 65 66 Expected<uint64_t> tsc_before_sleep = readTsc(); 67 sleep(SLEEP_SECS); 68 Expected<uint64_t> tsc_after_sleep = readTsc(); 69 70 // Skip the test if we are unable to read the TSC value. 71 if (!tsc_before_sleep) 72 GTEST_SKIP() << tsc_before_sleep.takeError(); 73 if (!tsc_after_sleep) 74 GTEST_SKIP() << tsc_after_sleep.takeError(); 75 76 std::chrono::nanoseconds converted_tsc_diff = 77 params->ToWallTime(*tsc_after_sleep) - 78 params->ToWallTime(*tsc_before_sleep); 79 80 std::chrono::microseconds acceptable_overhead(500); 81 82 ASSERT_GE(converted_tsc_diff.count(), SLEEP_NANOS.count()); 83 ASSERT_LT(converted_tsc_diff.count(), 84 (SLEEP_NANOS + acceptable_overhead).count()); 85 } 86