forked from idealvin/coost
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtime.cc
107 lines (80 loc) · 1.96 KB
/
time.cc
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
95
96
97
98
99
100
101
102
103
104
105
106
107
#ifndef _WIN32
#include "co/time.h"
#include <time.h>
#include <sys/time.h>
namespace co {
namespace now {
namespace xx {
#ifdef CLOCK_MONOTONIC
inline int64 ns() {
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return static_cast<int64>(t.tv_sec) * 1000000000 + t.tv_nsec;
}
inline int64 us() {
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return static_cast<int64>(t.tv_sec) * 1000000 + t.tv_nsec / 1000;
}
inline int64 ms() {
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return static_cast<int64>(t.tv_sec) * 1000 + t.tv_nsec / 1000000;
}
#else
// WARNING:
// If you are from the year 2262 or later, DO NOT use this,
// as nanoseconds since epoth (1970/1/1) may overflow then.
inline int64 ns() { return epoch::us() * 1000; }
inline int64 us() { return epoch::us(); }
inline int64 ms() { return epoch::ms(); }
#endif
} // xx
int64 ns() {
return xx::ns();
}
int64 us() {
return xx::us();
}
int64 ms() {
return xx::ms();
}
fastring str(const char* fm) {
time_t x = time(0);
struct tm t;
localtime_r(&x, &t);
char buf[256];
const size_t r = strftime(buf, sizeof(buf), fm, &t);
return fastring(buf, r);
}
} // now
namespace epoch {
int64 us() {
struct timeval t;
gettimeofday(&t, 0);
return static_cast<int64>(t.tv_sec) * 1000000 + t.tv_usec;
}
int64 ms() {
struct timeval t;
gettimeofday(&t, 0);
return static_cast<int64>(t.tv_sec) * 1000 + t.tv_usec / 1000;
}
} // epoch
} // co
namespace _xx {
namespace sleep {
void ms(uint32 n) {
struct timespec ts;
ts.tv_sec = n / 1000;
ts.tv_nsec = n % 1000 * 1000000;
while (nanosleep(&ts, &ts) == -1 && errno == EINTR);
}
void sec(uint32 n) {
struct timespec ts;
ts.tv_sec = n;
ts.tv_nsec = 0;
while (nanosleep(&ts, &ts) == -1 && errno == EINTR);
}
} // sleep
} // _xx
#endif