Coverage Report

Created: 2024-11-15 12:18

/root/bitcoin/src/util/time.cpp
Line
Count
Source (jump to first uncovered line)
1
// Copyright (c) 2009-2010 Satoshi Nakamoto
2
// Copyright (c) 2009-2022 The Bitcoin Core developers
3
// Distributed under the MIT software license, see the accompanying
4
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6
#include <util/time.h>
7
8
#include <compat/compat.h>
9
#include <tinyformat.h>
10
#include <util/check.h>
11
12
#include <atomic>
13
#include <chrono>
14
#include <string>
15
#include <thread>
16
17
0
void UninterruptibleSleep(const std::chrono::microseconds& n) { std::this_thread::sleep_for(n); }
18
19
static std::atomic<std::chrono::seconds> g_mock_time{}; //!< For testing
20
21
NodeClock::time_point NodeClock::now() noexcept
22
94.4k
{
23
94.4k
    const auto mocktime{g_mock_time.load(std::memory_order_relaxed)};
24
94.4k
    const auto ret{
25
94.4k
        mocktime.count() ?
26
94.3k
            mocktime :
27
94.4k
            std::chrono::system_clock::now().time_since_epoch()};
28
94.4k
    assert(ret > 0s);
29
94.4k
    return time_point{ret};
30
94.4k
};
31
32
856
void SetMockTime(int64_t nMockTimeIn) { SetMockTime(std::chrono::seconds{nMockTimeIn}); }
33
void SetMockTime(std::chrono::seconds mock_time_in)
34
857
{
35
857
    Assert(mock_time_in >= 0s);
36
857
    g_mock_time.store(mock_time_in, std::memory_order_relaxed);
37
857
}
38
39
std::chrono::seconds GetMockTime()
40
0
{
41
0
    return g_mock_time.load(std::memory_order_relaxed);
42
0
}
43
44
1
int64_t GetTime() { return GetTime<std::chrono::seconds>().count(); }
45
46
std::string FormatISO8601DateTime(int64_t nTime)
47
0
{
48
0
    const std::chrono::sys_seconds secs{std::chrono::seconds{nTime}};
49
0
    const auto days{std::chrono::floor<std::chrono::days>(secs)};
50
0
    const std::chrono::year_month_day ymd{days};
51
0
    const std::chrono::hh_mm_ss hms{secs - days};
52
0
    return strprintf("%04i-%02u-%02uT%02i:%02i:%02iZ", signed{ymd.year()}, unsigned{ymd.month()}, unsigned{ymd.day()}, hms.hours().count(), hms.minutes().count(), hms.seconds().count());
53
0
}
54
55
std::string FormatISO8601Date(int64_t nTime)
56
0
{
57
0
    const std::chrono::sys_seconds secs{std::chrono::seconds{nTime}};
58
0
    const auto days{std::chrono::floor<std::chrono::days>(secs)};
59
0
    const std::chrono::year_month_day ymd{days};
60
0
    return strprintf("%04i-%02u-%02u", signed{ymd.year()}, unsigned{ymd.month()}, unsigned{ymd.day()});
61
0
}
62
63
struct timeval MillisToTimeval(int64_t nTimeout)
64
0
{
65
0
    struct timeval timeout;
66
0
    timeout.tv_sec  = nTimeout / 1000;
67
0
    timeout.tv_usec = (nTimeout % 1000) * 1000;
68
0
    return timeout;
69
0
}
70
71
struct timeval MillisToTimeval(std::chrono::milliseconds ms)
72
0
{
73
0
    return MillisToTimeval(count_milliseconds(ms));
74
0
}