core_timing_util.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright 2008 Dolphin Emulator Project / 2017 Citra Emulator Project
  2. // Licensed under GPLv2+
  3. // Refer to the license.txt file included.
  4. #include "core/core_timing_util.h"
  5. #include <cinttypes>
  6. #include <limits>
  7. #include "common/logging/log.h"
  8. #include "common/uint128.h"
  9. namespace Core::Timing {
  10. constexpr u64 MAX_VALUE_TO_MULTIPLY = std::numeric_limits<s64>::max() / Hardware::BASE_CLOCK_RATE;
  11. s64 msToCycles(std::chrono::milliseconds ms) {
  12. if (static_cast<u64>(ms.count() / 1000) > MAX_VALUE_TO_MULTIPLY) {
  13. LOG_ERROR(Core_Timing, "Integer overflow, use max value");
  14. return std::numeric_limits<s64>::max();
  15. }
  16. if (static_cast<u64>(ms.count()) > MAX_VALUE_TO_MULTIPLY) {
  17. LOG_DEBUG(Core_Timing, "Time very big, do rounding");
  18. return Hardware::BASE_CLOCK_RATE * (ms.count() / 1000);
  19. }
  20. return (Hardware::BASE_CLOCK_RATE * ms.count()) / 1000;
  21. }
  22. s64 usToCycles(std::chrono::microseconds us) {
  23. if (static_cast<u64>(us.count() / 1000000) > MAX_VALUE_TO_MULTIPLY) {
  24. LOG_ERROR(Core_Timing, "Integer overflow, use max value");
  25. return std::numeric_limits<s64>::max();
  26. }
  27. if (static_cast<u64>(us.count()) > MAX_VALUE_TO_MULTIPLY) {
  28. LOG_DEBUG(Core_Timing, "Time very big, do rounding");
  29. return Hardware::BASE_CLOCK_RATE * (us.count() / 1000000);
  30. }
  31. return (Hardware::BASE_CLOCK_RATE * us.count()) / 1000000;
  32. }
  33. s64 nsToCycles(std::chrono::nanoseconds ns) {
  34. if (static_cast<u64>(ns.count() / 1000000000) > MAX_VALUE_TO_MULTIPLY) {
  35. LOG_ERROR(Core_Timing, "Integer overflow, use max value");
  36. return std::numeric_limits<s64>::max();
  37. }
  38. if (static_cast<u64>(ns.count()) > MAX_VALUE_TO_MULTIPLY) {
  39. LOG_DEBUG(Core_Timing, "Time very big, do rounding");
  40. return Hardware::BASE_CLOCK_RATE * (ns.count() / 1000000000);
  41. }
  42. return (Hardware::BASE_CLOCK_RATE * ns.count()) / 1000000000;
  43. }
  44. u64 CpuCyclesToClockCycles(u64 ticks) {
  45. const u128 temporal = Common::Multiply64Into128(ticks, Hardware::CNTFREQ);
  46. return Common::Divide128On32(temporal, static_cast<u32>(Hardware::BASE_CLOCK_RATE)).first;
  47. }
  48. } // namespace Core::Timing