aboutsummaryrefslogtreecommitdiffstats
path: root/ydb/core/base/cputime.h
blob: 6661a728fafc8edc982c15e381d99f8dbc604c12 (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
#pragma once
#include "appdata.h"

#include <util/system/datetime.h>
#include <library/cpp/actors/core/actor.h>

namespace NKikimr {
namespace NCpuTime {

class TCpuTimer {
    ui64 GetCpuTime() const {
        if (UseClockGettime) {
            return ThreadCPUTime();
        } else {
            return GetCycleCountFast();
        }
    }
public:
    TCpuTimer()
        : UseClockGettime(AppData()->FeatureFlags.GetEnableClockGettimeForUserCpuAccounting())
        , StartTime(GetCpuTime())
        , Counter(nullptr)
    {}

    TCpuTimer(TDuration& counter)
        : UseClockGettime(AppData()->FeatureFlags.GetEnableClockGettimeForUserCpuAccounting())
        , StartTime(GetCpuTime())
        , Counter(&counter)
    {}

    ~TCpuTimer() {
        if (Counter)
            *Counter += GetTime();
    }

    TDuration GetTime() const {
        if (UseClockGettime) {
            return TDuration::MicroSeconds(GetCpuTime() - StartTime);
        } else {
            double time = NHPTimer::GetSeconds(GetCpuTime() - StartTime);
            return TDuration::MicroSeconds(time * 1000000.0);
        }
    }
private:
    const bool UseClockGettime;
    const ui64 StartTime;
    TDuration* Counter;
};

} // namespace NCpuTime
} // namespace NKikimr