openFrameworks icon indicating copy to clipboard operation
openFrameworks copied to clipboard

std::chrono for FPS setting and counting

Open dimitre opened this issue 2 years ago • 1 comments

I'm working on some experiments on using internally std::chrono for FPS timing inside OF Core. I think we have some advantages as using the same code for all platforms, and maybe having better precision. here is an experiment with a fps counter



#include <chrono>
using namespace std::chrono;
using namespace std::chrono_literals;

struct fpsCounter {
public:
	int nAverages = 20;
	time_point<steady_clock> lastTick;
	using space = std::chrono::duration<long double, std::nano>;
	steady_clock::duration onesec = 1s;
	vector <space> intervals;
	space interval;
	space average;
	bool firstTick = true;
	int cursor = 0;

	void tick() {
		if (firstTick) {
			firstTick = false;
			lastTick = steady_clock::now();
			return;
		}

		interval = steady_clock::now() - lastTick;
		lastTick = steady_clock::now();
		if (intervals.size() < nAverages) {
			intervals.emplace_back(interval);
		} else {
			intervals[cursor] = interval;
			cursor = (cursor+1)%nAverages;
		}
	}
	
	float get() {
//		average = std::reduce(intervals.begin(), intervals.end())/intervals.size();
//		return onesec / average;
		average = std::reduce(intervals.begin(), intervals.end());
		return intervals.size() * onesec / average;
	}
} count;

it can be used like this

void ofApp::update() {
	count.tick();
	cout << "fps " << ofGetFrameRate() << endl;
	cout << "get " << count.get() << endl;
	cout << "---" << endl;
}

dimitre avatar Jan 18 '24 15:01 dimitre

related:

  • https://github.com/openframeworks/openFrameworks/pull/7867

dimitre avatar Jan 23 '24 00:01 dimitre

closed by

  • https://github.com/openframeworks/openFrameworks/pull/7867

dimitre avatar May 14 '24 00:05 dimitre