aboutsummaryrefslogtreecommitdiffstats
path: root/util/system/fasttime.cpp
blob: 4d40a42d63e62a90e4b4bba2012ece8087b0d89e (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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
#include "dynlib.h"
#include "fasttime.h"

#include <util/generic/singleton.h>
#include <util/generic/yexception.h>
#include <utility> 

#include <util/thread/singleton.h>

#if defined(_win_) || defined(_arm32_) || defined(_cygwin_)
ui64 InterpolatedMicroSeconds() {
    return MicroSeconds();
}
#else

    #include <dlfcn.h>
    #include <sys/time.h>

    #if defined(_musl_)
        #include <util/generic/hash.h>
        #include <util/generic/vector.h>
        #include <util/generic/string.h>

        #include <contrib/libs/linuxvdso/interface.h>
    #endif

namespace {
    using TTime = ui64;

    struct TSymbols {
        using TFunc = int (*)(struct timeval*, struct timezone*);

        inline TSymbols()
            : Func(nullptr)
        {
            // not DEFAULT, cause library/cpp/gettimeofday
            Func = reinterpret_cast<TFunc>(dlsym(RTLD_NEXT, "gettimeofday"));

    #if defined(_musl_)
            if (!Func) {
                Func = reinterpret_cast<TFunc>(NVdso::Function("__vdso_gettimeofday", "LINUX_2.6"));
            }
    #endif

            if (!Func) {
                Func = reinterpret_cast<TFunc>(Libc()->Sym("gettimeofday"));
            }
        }

        inline TTime SystemTime() {
            timeval tv;

            Zero(tv);

            Func(&tv, nullptr);

            return (((TTime)1000000) * (TTime)tv.tv_sec) + (TTime)tv.tv_usec;
        }

        static inline THolder<TDynamicLibrary> OpenLibc() {
            const char* libs[] = {
                "/lib/libc.so.8",
                "/lib/libc.so.7",
                "/lib/libc.so.6",
            };

            for (auto& lib : libs) {
                try {
                    return MakeHolder<TDynamicLibrary>(lib);
                } catch (...) {
                    // ¯\_(ツ)_/¯
                }
            }

            ythrow yexception() << "can not load libc";
        }

        inline TDynamicLibrary* Libc() {
            if (!Lib) {
                Lib = OpenLibc();
            }

            return Lib.Get();
        }

        THolder<TDynamicLibrary> Lib;
        TFunc Func;
    };

    static inline TTime SystemTime() {
        return Singleton<TSymbols>()->SystemTime();
    }

    struct TInitialTimes {
        inline TInitialTimes()
            : ITime(TimeBase())
            , IProc(RdtscBase())
        {
        }

        static TTime RdtscBase() {
            return GetCycleCount() / (TTime)1000;
        }

        static TTime TimeBase() {
            return SystemTime();
        }

        inline TTime Rdtsc() {
            return RdtscBase() - IProc;
        }

        inline TTime Time() {
            return TimeBase() - ITime;
        }

        const TTime ITime;
        const TTime IProc;
    };

    template <size_t N, class A, class B>
    class TLinePredictor {
    public:
        using TSample = std::pair<A, B>; 

        inline TLinePredictor()
            : C_(0)
            , A_(0)
            , B_(0)
        {
        }

        inline void Add(const A& a, const B& b) noexcept {
            Add(TSample(a, b));
        }

        inline void Add(const TSample& s) noexcept {
            S_[(C_++) % N] = s;
            if (C_ > 1) {
                ReCalc();
            }
        }

        inline B Predict(A a) const noexcept {
            return A_ + a * B_;
        }

        inline size_t Size() const noexcept {
            return C_;
        }

        inline bool Enough() const noexcept {
            return Size() >= N;
        }

        inline A LastX() const noexcept {
            return S_[(C_ - 1) % N].first;
        }

    private:
        inline void ReCalc() noexcept {
            const size_t n = Min(N, C_);

            double sx = 0;
            double sy = 0;
            double sxx = 0;
            double syy = 0;
            double sxy = 0;

            for (size_t i = 0; i < n; ++i) {
                const double x = S_[i].first;
                const double y = S_[i].second;

                sx += x;
                sy += y;
                sxx += x * x;
                syy += y * y;
                sxy += x * y;
            }

            B_ = (n * sxy - sx * sy) / (n * sxx - sx * sx);
            A_ = (sy - B_ * sx) / n;
        }

    private:
        size_t C_;
        TSample S_[N];
        double A_;
        double B_;
    };

    class TTimePredictor: public TInitialTimes {
    public:
        inline TTimePredictor()
            : Next_(1)
        {
        }

        inline TTime Get() {
            return GetBase() + ITime;
        }

    private:
        inline TTime GetBase() {
            const TTime x = Rdtsc();

            if (TimeToSync(x)) {
                const TTime y = Time();

                P_.Add(x, y);

                return y;
            }

            if (P_.Enough()) {
                return P_.Predict(x);
            }

            return Time();
        }

        inline bool TimeToSync(TTime x) {
            if (x > Next_) {
                Next_ = Min(x + x / 10, x + 1000000);

                return true;
            }

            return false;
        }

    private:
        TLinePredictor<16, TTime, TTime> P_;
        TTime Next_;
    };
}

ui64 InterpolatedMicroSeconds() {
    return FastTlsSingleton<TTimePredictor>()->Get();
}

#endif