C ++ 11模拟C#StopWatch

时间:2014-05-07 19:24:42

标签: c++

我正在寻找具有微秒精度的StopWatch类。我想必须可以使用std::chrono::high_resolution_clock来实现,你能建议一些实现吗?

1 个答案:

答案 0 :(得分:3)

这是一个示例,希望能够展示您创建Stopwatch类所需要做的所有事情。我将这个课程的创作留给你。

#include <iostream>
#include <chrono>

int main()
{
    // save some typing
    namespace cr = std::chrono;

    // you can replace this with steady_clock or system_clock
    typedef cr::high_resolution_clock my_clock;

    // get the clock time before operation.
    // note that this is a static function, and
    // we don't actually create a clock object
    auto start_time = my_clock::now();

    // perform some operation
    std::cin.ignore();

    // get the clock time after the operation
    auto end_time = my_clock::now();

    // get the elapsed time
    auto diff = end_time - start_time;

    // convert from the clock rate to a millisecond clock
    auto milliseconds = cr::duration_cast<cr::milliseconds>(diff);

    // get the clock count (i.e. the number of milliseconds)
    auto millisecond_count = milliseconds.count();

    std::cout << millisecond_count << '\n';
}