-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathframetimer.cpp
More file actions
88 lines (72 loc) · 2.26 KB
/
frametimer.cpp
File metadata and controls
88 lines (72 loc) · 2.26 KB
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
#include <fea/util/frametimer.hpp>
#include <algorithm>
#include <numeric>
#include <cmath>
namespace fea
{
FrameTimer::FrameTimer(int32_t pastFrames):
mMaxPastFrames(pastFrames),
mHasAtLeastOneTimePoint(false),
mFrameCount(0)
{
FEA_ASSERT(pastFrames > 1, "Too small value (" << pastFrames << ") given to FrameTimer. It must be at least 2 for the timer to function.");
}
void FrameTimer::sample()
{
if(mHasAtLeastOneTimePoint)
{
auto newTime = mClock.now();
auto elapsedMicroseconds = std::chrono::duration_cast<std::chrono::microseconds>(newTime - mLastTime).count();
float elapsedMilliseconds = elapsedMicroseconds / 1000.0f;
mLastFrameTimes.push_back(elapsedMilliseconds);
if(mLastFrameTimes.size() > mMaxPastFrames)
mLastFrameTimes.pop_front();
mLastTime = newTime;
}
else
{
mLastTime = mClock.now();
mHasAtLeastOneTimePoint = true;
}
mFrameCount++;
}
float FrameTimer::fps() const
{
float average = avgFrameTime();
if(average > 0.0f)
return 1000.0f / average;
else
return 0.0f;
}
float FrameTimer::avgFrameTime() const
{
if(!mLastFrameTimes.empty())
{
float totalTime = std::accumulate(mLastFrameTimes.begin(), mLastFrameTimes.end(), 0.0f);
return totalTime / mLastFrameTimes.size();
}
else
return 0.0f;
}
float FrameTimer::lastFrameTime() const
{
if(!mLastFrameTimes.empty())
return mLastFrameTimes.back();
else
return 0.0f;
}
float FrameTimer::avgDeviation() const
{
std::deque<float> frameTimes(mMaxPastFrames, 0.0f);
std::copy(mLastFrameTimes.begin(), mLastFrameTimes.end(), frameTimes.begin());
float averageFrameTime = avgFrameTime();
float deviationAccumulator = 0.0f;
for(float frameTime : frameTimes)
deviationAccumulator += std::abs(frameTime - averageFrameTime);
return deviationAccumulator / mMaxPastFrames;
}
int64_t FrameTimer::frameCount() const
{
return mFrameCount;
}
}