aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/lwtrace/perf.h
blob: d535247196d94c17d30cca6f0f26f2d5d715f577 (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
#pragma once

#include <util/system/types.h>
#include <util/thread/singleton.h>

namespace NLWTrace {
    struct TProbe;

    class TCpuTracker {
    private:
        const ui64 MinReportPeriod;

        // State
        bool Reporting = false;
        ui64 LastTs = 0;
        ui64 LastReportTs = 0;

        // Statistics
        ui64 MaxCycles;
        const TProbe* MaxProbe;
        ui64 MinCycles;
        ui64 ProbeCycles;
        ui64 Count;

    public:
        TCpuTracker();
        void Enter();
        void Exit(const TProbe* Probe);
        static TCpuTracker* TlsInstance() {
            struct TCpuTrackerkHolder {
                TCpuTracker Tracker;
            };
            return &FastTlsSingletonWithPriority<TCpuTrackerkHolder, 4>()->Tracker;
        }

    private:
        void AddStats(const TProbe* probe, ui64 cycles);
        void ResetStats();
        void Report();
        void ReportNotReentrant();
        static double MilliSeconds(ui64 cycles);
    };

    class TScopedThreadCpuTracker {
    private:
        const TProbe* Probe;
        TCpuTracker* Tracker;

    public:
        template <class T>
        explicit TScopedThreadCpuTracker(const T& probe)
            : Probe(&probe.Probe)
            , Tracker(TCpuTracker::TlsInstance())
        {
            Tracker->Enter();
        }

        ~TScopedThreadCpuTracker() {
            Tracker->Exit(Probe);
        }
    };

}