openframeworks / openFrameworks

openFrameworks is a community-developed cross platform toolkit for creative coding in C++.
http://openframeworks.cc
Other
9.89k stars 2.55k forks source link

std::chrono for FPS setting #7866

Closed dimitre closed 3 months ago

dimitre commented 7 months ago

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 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 commented 7 months ago

related:

dimitre commented 3 months ago

closed by