CGI/exercise2/include/timer.h

48 lines
1,007 B
C
Raw Normal View History

2018-11-28 11:19:51 +00:00
#pragma once
#include <ctime>
#include <iostream>
#include <ratio>
#include <chrono>
typedef std::chrono::duration<int, std::milli> milliseconds_type;
2019-01-05 11:45:02 +00:00
class Counter
{
private:
2018-11-28 11:19:51 +00:00
int max;
int n;
2019-01-05 11:45:02 +00:00
std::chrono::system_clock::time_point last_time;
2018-11-28 11:19:51 +00:00
milliseconds_type update_interval;
2019-01-05 11:45:02 +00:00
public:
2018-11-28 11:19:51 +00:00
Counter(int max, float interval)
2019-01-05 11:45:02 +00:00
: max(max), update_interval((int)(interval * 1000.0f))
2018-11-28 11:19:51 +00:00
{
last_time = std::chrono::high_resolution_clock::now();
n = 0;
}
~Counter() {}
2019-01-05 11:45:02 +00:00
int get_counter()
{
2018-11-28 11:19:51 +00:00
auto new_time = std::chrono::high_resolution_clock::now();
milliseconds_type time_difference = std::chrono::duration_cast<milliseconds_type>(new_time - last_time);
2019-01-05 11:45:02 +00:00
if (time_difference.count() >= update_interval.count())
{
2018-11-28 11:19:51 +00:00
last_time += update_interval;
n++;
2019-01-05 11:45:02 +00:00
if (n >= max)
{
2018-11-28 11:19:51 +00:00
n = n - max;
abort();
}
}
return n;
}
};