1 |
|
---|
2 | #include <boost/cstdint.hpp>
|
---|
3 | #include <boost/asio/basic_deadline_timer.hpp>
|
---|
4 |
|
---|
5 | struct TimerTraits
|
---|
6 | {
|
---|
7 | private:
|
---|
8 | static boost::int64_t performance_freq_;
|
---|
9 |
|
---|
10 | public:
|
---|
11 | // The time type. This type has no constructor that takes a boost::int64_t to ensure
|
---|
12 | // that the timer can only be used with relative times.
|
---|
13 | class time_type
|
---|
14 | {
|
---|
15 | public:
|
---|
16 | time_type() : ticks_(0) {}
|
---|
17 | private:
|
---|
18 | friend struct TimerTraits;
|
---|
19 | boost::int64_t ticks_;
|
---|
20 | };
|
---|
21 |
|
---|
22 | // The duration type.
|
---|
23 | class duration_type
|
---|
24 | {
|
---|
25 | public:
|
---|
26 | duration_type() : ticks_(0) {}
|
---|
27 | duration_type(boost::int64_t ticks) : ticks_(ticks) {}
|
---|
28 | private:
|
---|
29 | friend struct TimerTraits;
|
---|
30 | boost::int64_t ticks_;
|
---|
31 | };
|
---|
32 |
|
---|
33 | // Get the current time.
|
---|
34 | static time_type now();
|
---|
35 |
|
---|
36 | // Add a duration to a time.
|
---|
37 | static time_type add(const time_type& t, const duration_type& d)
|
---|
38 | {
|
---|
39 | time_type result;
|
---|
40 | result.ticks_ = t.ticks_ + d.ticks_;
|
---|
41 | return result;
|
---|
42 | }
|
---|
43 |
|
---|
44 | // Subtract one time from another.
|
---|
45 | static duration_type subtract(const time_type& t1, const time_type& t2)
|
---|
46 | {
|
---|
47 | return duration_type(t1.ticks_ - t2.ticks_);
|
---|
48 | }
|
---|
49 |
|
---|
50 | // Test whether one time is less than another.
|
---|
51 | static bool less_than(const time_type& t1, const time_type& t2)
|
---|
52 | {
|
---|
53 | boost::int64_t difference = t2.ticks_ - t1.ticks_;
|
---|
54 |
|
---|
55 | // boost::int64_t tick count values wrap periodically, so we'll use a heuristic that
|
---|
56 | // says that if subtracting t1 from t2 yields a value smaller than 2^63,
|
---|
57 | // (i.e. a positive number in signed 64-bit arithmetic)
|
---|
58 | // then t1 is probably less than t2. This means that we can't handle
|
---|
59 | // durations larger than 2^63, which shouldn't be a problem in practice.
|
---|
60 |
|
---|
61 | return difference > 0;
|
---|
62 | }
|
---|
63 |
|
---|
64 | // Convert to POSIX duration type.
|
---|
65 | static boost::posix_time::time_duration to_posix_duration(
|
---|
66 | const duration_type& d);
|
---|
67 |
|
---|
68 | // Convert milliseconds to duration type
|
---|
69 | static boost::int64_t milliseconds_to_duration(boost::uint32_t milliseconds);
|
---|
70 | };
|
---|
71 |
|
---|
72 | typedef boost::asio::basic_deadline_timer<
|
---|
73 | boost::int64_t, TimerTraits> TimerImpl;
|
---|