core_timing_util.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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() / BASE_CLOCK_RATE;
  11. s64 usToCycles(s64 us) {
  12. if (us / 1000000 > MAX_VALUE_TO_MULTIPLY) {
  13. LOG_ERROR(Core_Timing, "Integer overflow, use max value");
  14. return std::numeric_limits<s64>::max();
  15. }
  16. if (us > MAX_VALUE_TO_MULTIPLY) {
  17. LOG_DEBUG(Core_Timing, "Time very big, do rounding");
  18. return BASE_CLOCK_RATE * (us / 1000000);
  19. }
  20. return (BASE_CLOCK_RATE * us) / 1000000;
  21. }
  22. s64 usToCycles(u64 us) {
  23. if (us / 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 (us > MAX_VALUE_TO_MULTIPLY) {
  28. LOG_DEBUG(Core_Timing, "Time very big, do rounding");
  29. return BASE_CLOCK_RATE * static_cast<s64>(us / 1000000);
  30. }
  31. return (BASE_CLOCK_RATE * static_cast<s64>(us)) / 1000000;
  32. }
  33. s64 nsToCycles(s64 ns) {
  34. if (ns / 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 (ns > MAX_VALUE_TO_MULTIPLY) {
  39. LOG_DEBUG(Core_Timing, "Time very big, do rounding");
  40. return BASE_CLOCK_RATE * (ns / 1000000000);
  41. }
  42. return (BASE_CLOCK_RATE * ns) / 1000000000;
  43. }
  44. s64 nsToCycles(u64 ns) {
  45. if (ns / 1000000000 > MAX_VALUE_TO_MULTIPLY) {
  46. LOG_ERROR(Core_Timing, "Integer overflow, use max value");
  47. return std::numeric_limits<s64>::max();
  48. }
  49. if (ns > MAX_VALUE_TO_MULTIPLY) {
  50. LOG_DEBUG(Core_Timing, "Time very big, do rounding");
  51. return BASE_CLOCK_RATE * (static_cast<s64>(ns) / 1000000000);
  52. }
  53. return (BASE_CLOCK_RATE * static_cast<s64>(ns)) / 1000000000;
  54. }
  55. u64 CpuCyclesToClockCycles(u64 ticks) {
  56. const u128 temporal = Common::Multiply64Into128(ticks, CNTFREQ);
  57. return Common::Divide128On32(temporal, static_cast<u32>(BASE_CLOCK_RATE)).first;
  58. }
  59. } // namespace Core::Timing