2022-01-20 18:27:56 +00:00
|
|
|
// This file Copyright 2010-2022 Mnemosyne LLC.
|
|
|
|
// It may be used under GPLv2 (SPDX: GPL-2.0), GPLv3 (SPDX: GPL-3.0),
|
|
|
|
// or any future license endorsed by Mnemosyne LLC.
|
|
|
|
// License text can be found in the licenses/ folder.
|
2010-03-08 04:29:58 +00:00
|
|
|
|
2017-11-14 20:21:28 +00:00
|
|
|
#pragma once
|
|
|
|
|
2010-03-08 04:29:58 +00:00
|
|
|
#ifndef __TRANSMISSION__
|
2017-04-19 12:04:45 +00:00
|
|
|
#error only libtransmission should #include this header.
|
2010-03-08 04:29:58 +00:00
|
|
|
#endif
|
|
|
|
|
2021-10-07 13:33:55 +00:00
|
|
|
#include <array>
|
|
|
|
#include <cstddef> // size_t
|
|
|
|
#include <ctime> // time_t
|
|
|
|
#include <numeric> // std::accumulate
|
2020-08-11 18:11:55 +00:00
|
|
|
|
2010-03-08 04:29:58 +00:00
|
|
|
/**
|
2021-10-07 13:33:55 +00:00
|
|
|
* A short-term memory object that remembers how many times something
|
|
|
|
* happened over the last N seconds. tr_peer uses it to count how many
|
|
|
|
* bytes transferred to estimate the speed over the last N seconds.
|
2010-03-08 04:29:58 +00:00
|
|
|
*/
|
2021-10-07 13:33:55 +00:00
|
|
|
class tr_recentHistory
|
2011-02-23 06:01:16 +00:00
|
|
|
{
|
2021-10-07 13:33:55 +00:00
|
|
|
public:
|
|
|
|
/**
|
|
|
|
* @brief add a counter to the recent history object.
|
|
|
|
* @param when the current time in sec, such as from tr_time()
|
|
|
|
* @param n how many items to add to the history's counter
|
|
|
|
*/
|
|
|
|
void add(time_t now, size_t n)
|
|
|
|
{
|
|
|
|
if (slices[newest].time != now)
|
|
|
|
{
|
|
|
|
newest = (newest + 1) % TR_RECENT_HISTORY_PERIOD_SEC;
|
|
|
|
slices[newest].time = now;
|
|
|
|
}
|
2011-04-06 23:27:11 +00:00
|
|
|
|
2021-10-07 13:33:55 +00:00
|
|
|
slices[newest].n += n;
|
|
|
|
}
|
2011-04-06 23:27:11 +00:00
|
|
|
|
2021-10-07 13:33:55 +00:00
|
|
|
/**
|
|
|
|
* @brief count how many events have occurred in the last N seconds.
|
|
|
|
* @param when the current time in sec, such as from tr_time()
|
|
|
|
* @param seconds how many seconds to count back through.
|
|
|
|
*/
|
|
|
|
size_t count(time_t now, unsigned int age_sec) const
|
2017-04-19 12:04:45 +00:00
|
|
|
{
|
2021-10-07 13:33:55 +00:00
|
|
|
time_t const oldest = now - age_sec;
|
2010-03-08 04:29:58 +00:00
|
|
|
|
2021-10-07 13:33:55 +00:00
|
|
|
return std::accumulate(
|
|
|
|
std::begin(slices),
|
|
|
|
std::end(slices),
|
|
|
|
size_t{ 0 },
|
|
|
|
[&oldest](size_t sum, auto const& slice) { return slice.time >= oldest ? sum + slice.n : sum; });
|
|
|
|
}
|
2010-03-08 04:29:58 +00:00
|
|
|
|
2021-10-07 13:33:55 +00:00
|
|
|
private:
|
|
|
|
inline auto static constexpr TR_RECENT_HISTORY_PERIOD_SEC = size_t{ 60 };
|
|
|
|
|
|
|
|
int newest = 0;
|
|
|
|
|
|
|
|
struct slice_t
|
|
|
|
{
|
|
|
|
size_t n = 0;
|
|
|
|
time_t time = 0;
|
|
|
|
};
|
|
|
|
|
|
|
|
std::array<slice_t, TR_RECENT_HISTORY_PERIOD_SEC> slices = {};
|
|
|
|
};
|