【问题标题】:Getting a time difference in milliseconds以毫秒为单位获取时间差
【发布时间】:2015-07-18 04:42:05
【问题描述】:

我正在尝试做一些我认为非常简单的事情,但我到处寻找,但我无法弄清楚。我也是 C++ 新手,对模板等没有很好的了解。

我只需要一个函数来测量从程序启动到某个点的时间(以毫秒为单位),例如:

class timeCounter {

    private:
        long startTime;
        long currentTime;
        long timeDifference;
    public:
        long getTime();
}

timeCounter::timeCounter () {
    startTime = time.now();
}

long timeCounter::getTimePassed () {
    currentTime = time.now();
    timeDifference = timeNow - timeStart;
    return timeDifference;
}

我尝试过使用clock() / CLOCKS_PER_SECONDS,但结果慢于一秒。

谁能帮帮我?

非常感谢!

【问题讨论】:

标签: c++ time


【解决方案1】:

我最近正在编写一个类似的系统来获取游戏引擎的增量时间。

使用std::chrono 库,这是一个示例:

#include <iostream>
#include <chrono>
#include <thread>

class timer
{
    // alias our types for simplicity
    using clock             = std::chrono::system_clock;
    using time_point_type   = std::chrono::time_point < clock, std::chrono::milliseconds > ;
public:
    // default constructor that stores the start time
    timer()
    {
        start = std::chrono::time_point_cast<std::chrono::milliseconds>(clock::now());
    }

    // gets the time elapsed from construction.
    long /*milliseconds*/ getTimePassed()
    {
        // get the new time
        auto end = clock::now();

        // return the difference of the times
        return (end - start).count();
    }

private:
    time_point_type start;
};

int main()
{
    timer t;

    std::this_thread::sleep_for(std::chrono::seconds(5));

    std::cout << t.getTimePassed();

    std::cin.get();
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-26
  • 2017-08-05
  • 2013-05-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多