Created
October 20, 2016 03:04
-
-
Save hikilaka/2b6166aa5b99f69293ec32bf7e50cbdb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <chrono> | |
#include <cmath> | |
#include <functional> | |
#include <iomanip> | |
#include <iostream> | |
#include <thread> | |
template <typename clock, | |
std::size_t cycle_rate, | |
typename cycle_duration> | |
class engine { | |
public: | |
engine() = default; | |
~engine() = default; | |
void loop(std::function<void()> work) { | |
auto last_update = clock::now(); | |
while(running) { | |
work(); // temporary | |
auto now = clock::now(); | |
auto sleep_time = std::chrono::duration_cast<cycle_duration>(tick_rate - (now - last_update)); | |
load = std::abs(static_cast<double>((now - last_update).count())) / static_cast<double>(cycle_rate); | |
load /= 10000.00; | |
if (sleep_time.count() > 0) | |
std::this_thread::sleep_for(sleep_time); | |
last_update = clock::now(); | |
} | |
} | |
void start() { running = true; } | |
void stop() { running = false; } | |
double work_load() { return load; } | |
private: | |
bool running = false; | |
double load = 0.0; | |
const cycle_duration tick_rate = cycle_duration(cycle_rate); | |
}; | |
int main() { | |
using clock = std::chrono::high_resolution_clock; | |
using cycle_duration = std::chrono::milliseconds; | |
using rs2_engine = engine<clock, 600, cycle_duration>; | |
rs2_engine e; | |
e.start(); | |
e.loop([&e] { | |
std::cout << std::setprecision(4) | |
<< "engine load: " << e.work_load() << "%" | |
<< std::endl; | |
std::this_thread::sleep_for(std::chrono::milliseconds(200)); | |
}); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment