-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtime_test.cpp
94 lines (78 loc) · 2.37 KB
/
time_test.cpp
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
#include "time.hpp"
// std
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <list>
#include <set>
#include <sstream>
#include <vector>
#include <thread>
// local
#include "simple_unit_test.hpp"
#include "raii.hpp"
namespace util::test {
uint64_t get_epoch_from_system()
{
FILE* f = popen( "date \"+%s\"", "r" );
util::RAII< FILE* > guard( f, [](FILE* f) { pclose(f); } );
char buffer[128] = {};
fread( &buffer[0], std::size(buffer), 1, f );
return std::strtoull( &buffer[0], nullptr, 10 );
}
template <typename T,
typename A,
template<typename, typename> class C,
typename = std::enable_if_t<
std::is_same_v<C<T, A>, std::list<T, A>> ||
std::is_same_v<C<T, A>, std::vector<T, A>>>>
std::string join(const C<T, A>& container, std::string separator = ", ")
{
std::stringstream result;
result << "[";
const char* ps = nullptr;
for ( const auto& t : container )
{
result << ( ps ? ps : "") << t;
ps = separator.data();
}
result << "]";
return result.str();
}
}
namespace std {
template <typename T,
typename A,
template<typename, typename> class C,
typename = std::enable_if_t<
std::is_same_v<C<T, A>, std::list<T, A>> ||
std::is_same_v<C<T, A>, std::vector<T, A>>>>
ostream& operator<<(ostream& os, const C<T, A>& container)
{
using namespace util::test;
return os << join(container, ", ");
}
}
//
int main(int argc, char* argv[])
{
using namespace util::test;
using namespace std::literals;
// check we match the system time
ASSERT_EQUAL( get_epoch_from_system(), util::get_ns_since_epoch()/1'000'000'000 );
// check we get different and successive numbers
std::vector<uint64_t> times(10000);
std::set<uint64_t> unique_times;
for (size_t i=0; i<times.size(); ++i)
{
times[i] = util::get_ns_since_epoch();
unique_times.insert(times[i]);
std::this_thread::sleep_for(10us);
}
ASSERT_EQUAL( times.size(), unique_times.size() );
std::vector sorted_times{ times };
std::ranges::sort(sorted_times);
ASSERT_EQUAL( times, sorted_times );
return failed_tests;
}