c++使运行时间独立于平台



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

我用glutGet(GLUT_ELAPSED_TIME)来做那件事。但是在包含glew之后,编译器再也找不到glutGet函数了(奇怪)。所以我需要一个替代方案。

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

我可以使用C++11。

我认为在C++11之前没有内置高分辨率时钟。如果你不能使用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;
};
  1. Boost提供类似std::chrono的时钟:Boost::chrono
  2. 您应该考虑使用std::chrono::steady_clock(或boost等效物),而不是std::chrono::high_resolution_clock-或者至少确保std::strono::steady_clock::is_steady()==true-如果您想使用它来计算持续时间,因为非稳定时钟返回的时间甚至可能随着物理时间的推移而减少

最新更新