aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/ipreg/stopwatch.cpp
blob: 31d99d2758d561082cd72e2f172ab1a1501ab92a (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
#include "stopwatch.h"

#include <util/stream/str.h>

namespace NIPREG {

TStopWatch::TStopWatch() {
    Start = TInstant::Now();
}

TStopWatch::~TStopWatch() {
    try {
        if (TaskRunning)
            StopTask();

        Cerr << "Everything done in " << FormatTime(TInstant::Now() - Start) << Endl;
    } catch (...) {
        // not much problem if we can't write the summary
    }
}

void TStopWatch::StartTask(const TString& message) {
    StopTask();

    ++TaskOrdNum;
    TaskStart = TInstant::Now();
    TaskRunning = true;
    Cerr << TaskOrdNum << ". " << message << "...\n";
}

void TStopWatch::StopTask() {
    if (TaskRunning) {
        Cerr << "Done in " << FormatTime(TInstant::Now() - TaskStart) << Endl;
        TaskRunning = false;
    }
}

TString TStopWatch::FormatTime(const TDuration& dur) {
    auto sec = dur.Seconds();

    TStringStream ss;

    if (sec < 60)
        ss << sec << "s";
    else if (sec < 3600)
        ss << sec / 60 << "m " << sec % 60 << "s";
    else
        ss << sec / 3600 << "h " << (sec / 60) % 60 << "m";

    return ss.Str();
}

}