Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ get elapsed time platform independent

For a game I wanna measure the time that has passed since the last frame.

I used glutGet(GLUT_ELAPSED_TIME) to do that. But after including glew the compiler can't find the glutGet function anymore (strange). So I need an alternative.

Most sites I found so far suggest using clock in ctime but that function only measures the cpu time of the program not the real time! The time function in ctime is only accurate to seconds. I need at least millisecond accuracy.

I can use C++11.

like image 863
relgukxilef Avatar asked Mar 23 '23 04:03

relgukxilef


2 Answers

I don't think there is a high resolution clock built-in C++ before C++11. If you are unable to use C++11 you have to either fix your error with glut and glew or use the platform dependent timer functions.

#include <chrono>
class Timer {
public:
    Timer() {
        reset();
    }
    void reset() {
        m_timestamp = std::chrono::high_resolution_clock::now();
    }
    float diff() {
        std::chrono::duration<float> fs = std::chrono::high_resolution_clock::now() - m_timestamp;
        return fs.count();
    }
private:
    std::chrono::high_resolution_clock::time_point m_timestamp;
};
like image 186
typ1232 Avatar answered Apr 05 '23 09:04

typ1232


  1. Boost provides std::chrono like clocks: boost::chrono
  2. You should consider using std::chrono::steady_clock (or boost equivalent) as opposed to std::chrono::high_resolution_clock - or at least ensure std::chrono::steady_clock::is_steady() == true - if you want to use it to calculate duration, as the time returned by a non-steady clock might even decrease as physical time moves forward.
like image 24
Iwan Aucamp Avatar answered Apr 05 '23 08:04

Iwan Aucamp