c ++获得独立于平台的经过时间

rel*_*lef 4 c++ cross-platform

对于游戏,我想测量自上一帧以来经过的时间。

我曾经glutGet(GLUT_ELAPSED_TIME)这样做过。但是在包含 glew 之后,编译器再也找不到 glutGet 函数了(奇怪)。所以我需要一个替代方案。

到目前为止,我发现的大多数网站都建议在 ctime 中使用时钟,但该功能仅测量程序的 CPU 时间,而不是实时时间!ctime 中的时间函数只精确到秒。我需要至少毫秒精度。

我可以使用 C++11。

typ*_*232 5

我认为在 C++11 之前 C++ 没有内置高分辨率时钟。如果您无法使用 C++11,则必须使用 glut 和 glew 修复错误或使用平台相关的计时器函数。

#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;
};
Run Code Online (Sandbox Code Playgroud)