aboutsummaryrefslogtreecommitdiff
path: root/src/common/wall_clock.cpp
blob: d0c6893db4b6d38b7bf2de14eceb1b16c05c2526 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include "common/steady_clock.h"
#include "common/wall_clock.h"

#ifdef ARCHITECTURE_x86_64
#include "common/x64/cpu_detect.h"
#include "common/x64/native_clock.h"
#include "common/x64/rdtsc.h"
#endif

#ifdef HAS_NCE
#include "common/arm64/native_clock.h"
#endif

namespace Common {

class StandardWallClock final : public WallClock {
public:
    explicit StandardWallClock() {}

    void Reset() override {
        start_time = std::chrono::system_clock::now();
    }

    std::chrono::nanoseconds GetTimeNS() const override {
        return std::chrono::duration_cast<std::chrono::nanoseconds>(
            std::chrono::system_clock::now().time_since_epoch());
    }

    std::chrono::microseconds GetTimeUS() const override {
        return std::chrono::duration_cast<std::chrono::microseconds>(
            std::chrono::system_clock::now().time_since_epoch());
    }

    std::chrono::milliseconds GetTimeMS() const override {
        return std::chrono::duration_cast<std::chrono::milliseconds>(
            std::chrono::system_clock::now().time_since_epoch());
    }

    s64 GetCNTPCT() const override {
        return GetUptime() * NsToCNTPCTRatio::num / NsToCNTPCTRatio::den;
    }

    s64 GetGPUTick() const override {
        return GetUptime() * NsToGPUTickRatio::num / NsToGPUTickRatio::den;
    }

    s64 GetUptime() const override {
        return std::chrono::duration_cast<std::chrono::nanoseconds>(
                   std::chrono::system_clock::now() - start_time)
            .count();
    }

    bool IsNative() const override {
        return false;
    }

private:
    std::chrono::system_clock::time_point start_time{};
};

std::unique_ptr<WallClock> CreateOptimalClock() {
#if defined(ARCHITECTURE_x86_64)
    const auto& caps = GetCPUCaps();

    if (caps.invariant_tsc && caps.tsc_frequency >= std::nano::den) {
        return std::make_unique<X64::NativeClock>(caps.tsc_frequency);
    } else {
        // Fallback to StandardWallClock if the hardware TSC
        // - Is not invariant
        // - Is not more precise than 1 GHz (1ns resolution)
        return std::make_unique<StandardWallClock>();
    }
#elif defined(HAS_NCE)
    return std::make_unique<Arm64::NativeClock>();
#else
    return std::make_unique<StandardWallClock>();
#endif
}

std::unique_ptr<WallClock> CreateStandardWallClock() {
    return std::make_unique<StandardWallClock>();
}

} // namespace Common