summaryrefslogtreecommitdiffstats
path: root/RateCalculator.cpp
blob: bfc268e491eaa779b19182e45437de7de96d6d7e (plain) (blame)
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
#include "RateCalculator.h"

void RateCalculator::addBytes(qint64 bytes)
{
	if (!m_timer.isValid())
		start();
	m_segments.prepend(qMakePair(m_timer.restart(), bytes));
	m_byteSum += bytes;
}
void RateCalculator::updateTotalBytes(qint64 bytes)
{
	addBytes(bytes - m_byteSum);
}
void RateCalculator::start()
{
	m_byteSum = 0;
	m_segments.clear();
	m_timer.restart();
}
void RateCalculator::stop()
{
	m_timer.invalidate();
}
void RateCalculator::reset()
{
	stop();
	start();
}
double RateCalculator::rate(qint64 interval) const
{
	qint64 time = 0;
	qint64 bytes = 0;
	QPair<qint64, qint64> i;
	foreach (i, m_segments) {
		time += i.first;
		bytes += i.second;
		if (interval > 0 && time >= interval)
			break;
	}
	return static_cast<double>(bytes) / static_cast<double>(time);
}
double RateCalculator::elapsed() const
{
	qint64 time = 0;
	QPair<qint64, qint64> i;
	foreach (i, m_segments)
		time += i.first;
	return time;
}