YSTest: ytimer.cpp 源文件

YSTest PreAlpha_b400_20130424 The YSLib Test Project

- 首页
- 相关页面
- 模块
- 命名空间
- 类
- 文件

- 文件列表
- 文件成员

全部 类 命名空间 文件 函数 变量 类型定义 枚举 枚举值 友元 宏定义 组 页
ytimer.cpp
浏览该文件的文档.
1 ﻿/*
2 Copyright (C) by Franksoft 2010 - 2011.
3
4 This file is part of the YSLib project, and may only be used,
5 modified, and distributed under the terms of the YSLib project
6 license, LICENSE.TXT. By continuing to use, modify, or distribute
7 this file you indicate that you have read the license and
8 understand and accept it fully.
9 */
10
28 #include "YSLib/Service/ytimer.h"
29 #include <ystdex/iterator.hpp>
30
31 YSL_BEGIN
32
33 YSL_BEGIN_NAMESPACE(Timers)
34
35 namespace
36 {
37 bool NotInitialized(true);
38
39 void
40 Init(Timer& tmr, bool b)
41 {
42 if(YB_UNLIKELY(NotInitialized))
43 {
44 StartTicks();
45 NotInitialized = false;
46 }
47 if(b)
48 Activate(tmr);
49 }
50
51
52 inline TimePoint
53 GetTickPoint()
54 {
55 return TimePoint(TimeSpan(GetTicks()));
56 }
57 }
58
59 void
60 Delay(const TimeSpan& ms)
61 {
62 const auto end(GetTickPoint() + ms);
63
64 while(GetTickPoint() < end)
65 ;
66 }
67
68
69 Timer::TimerMap Timer::mTimers;
70
71 Timer::Timer(const Duration& i, bool b)
72 : nBase(), nInterval(i)
73 {
74 Init(*this, b);
75 }
76
77
78 bool
79 Timer::IsActive() const
80 {
81 try
82 {
83 mTimers.at(GetObjectID());
84 return true;
85 }
86 catch(std::out_of_range&)
87 {}
88 return false;
89 }
90
91 void
92 Timer::SetInterval(const Duration& i)
93 {
94 nInterval = i;
95 if(YB_UNLIKELY(nInterval == Duration::zero()))
96 Deactivate(*this);
97 }
98
99 bool
100 Timer::Refresh()
101 {
102 const auto tick(HighResolutionClock::now());
103
104 if(YB_LIKELY(tick < nBase + nInterval))
105 return false;
106 nBase = tick - (tick - nBase) % nInterval;
107 return true;
108 }
109
110 bool
111 Timer::RefreshAll()
112 {
113 using ystdex::get_value;
114
115 bool t(false);
116
117 std::for_each(mTimers.begin() | get_value, mTimers.end() | get_value,
118 [&](Timer* const& pTmr){
119 if(YB_LIKELY(pTmr))
120 t |= pTmr->Refresh();
121 });
122 return t;
123 }
124
125 void
126 Timer::ResetAll()
127 {
128 using ystdex::get_value;
129
130 std::for_each(mTimers.begin() | get_value, mTimers.end() | get_value,
131 [](Timer* const& pTmr){
132 if(YB_LIKELY(pTmr))
133 pTmr->Reset();
134 });
135 }
136
137 void
138 Activate(Timer& tmr)
139 {
140 if(tmr.nInterval != Duration::zero())
141 {
142 Timer::mTimers.insert(make_pair(tmr.GetObjectID(), &tmr));
143 tmr.nBase = HighResolutionClock::now();
144 }
145 }
146
147 void
148 Deactivate(Timer& tmr)
149 {
150 Timer::mTimers.erase(tmr.GetObjectID());
151 }
152
153 YSL_END_NAMESPACE(Timers)
154
155 YSL_END
156