-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmperiod.cxx
108 lines (90 loc) · 1.68 KB
/
mperiod.cxx
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
/*
*
*
*/
#include <iostream>
#include <cstdio>
#include <unistd.h>
#include <sys/time.h>
#include <errno.h>
class mPeriod {
public:
#if 0
mPeriod();
virtual ~mPeriod();
#endif
int reset();
double tap();
double get_mean() {return m_mean;};
protected:
private:
double mean();
struct timeval m_at_start;
struct timeval m_now;
long long int m_ntap;
double m_mean;
};
#if 0
mPeriod::mPeriod()
{
return;
}
mPeriod::~mPeriod()
{
std::cout << "# Period destructed" << std::endl;
return;
}
#endif
int mPeriod::reset()
{
int ret = gettimeofday(&m_at_start, NULL);
if (ret != 0) perror("mPeriod::reset");
m_ntap = 0;
m_mean = 0;
return ret;
}
double mPeriod::tap()
{
int ret = gettimeofday(&m_now, NULL);
if (ret != 0) {
perror("mPeriod::tap");
return ret;
}
m_ntap++;
double val = mean();
m_at_start.tv_usec = m_now.tv_usec;
m_at_start.tv_sec = m_now.tv_sec;
return val;
}
double mPeriod::mean()
{
int dusec =m_now.tv_usec - m_at_start.tv_usec;
int dsec = m_now.tv_sec - m_at_start.tv_sec;
int diff = dsec * 1000 + (dusec / 1000);
//std::cout << "#D " << m_ntap << " mean: " << m_mean << " diff: " << diff;
if (m_ntap > 1) {
m_mean = (m_mean * (m_ntap - 1) + diff) / m_ntap;
} else
if (m_ntap == 1) {
m_mean = static_cast<double>(diff);
} else {
m_mean = 0;
}
//std::cout << " mean af: " << m_mean << std::endl;
return m_mean ;
}
#ifdef PERIOD_TEST_MAIN
#include <cstdlib>
int main(int argc, char *argv[])
{
mPeriod p;
p.reset();
for (int i = 0 ; i < 200 ; i++) {
usleep(10000
+ ((static_cast<double>(rand()) / RAND_MAX) * 10000));
double mean = p.tap();
std::cout << "period : " << mean << std::endl;;
}
return 0;
}
#endif