CGI/exercise2/include/timer.h
2019-01-05 12:45:02 +01:00

48 lines
No EOL
1,007 B
C++

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