Several questions about <chrono> header in C++ 11

大兔子大兔子 提交于 2019-12-03 12:05:52
bames53
  1. Correct

    According to the standard:

    system_clock represent[s] wall clock time from the system-wide realtime clock.

    The <chrono> library does not provide a mechanism for measuring CPU time, so if you want that you'll have to fall back on the old <ctime> library and use std::clock().

    (And if you're targeting Windows you'll have to fall back on whatever platform-specific API Windows provides for getting CPU time since, as you point out, their std::clock() doesn't work correctly.)

    system_clock is more like a counterpart to std::time() than to std::clock(). (E.g., note that system_clock provides conversions between system_clock::time_points and time_t.) I imagine that the lack of a clock in <chrono> for measuring CPU time is due to time constraints on the standard committee and the fact that that functionality is less used than the system's wall clock and real-time clocks.

    If you want CPU time but also want the benefits that <chrono> provides, you should implement a clock type that conforms to the Clock concept outlined in the standard and which provides CPU time, perhaps implemented internally using std::clock().

  2. The line that says

    int elapsed_seconds = std::chrono::duration_cast<std::chrono::seconds>
                        (end-start).count();
    

    is what causes the time to be rounded to an integral number of seconds. You can choose any period you'd like, or you can use a floating point representation in order to allow non-integral values:

    std::int64_t elapsed_attoseconds =
        std::chrono::duration_cast<std::chrono::duration<std::int64_t, std::atto>>
            (end-start).count();
    
    double elapsed_seconds =
        std::chrono::duration_cast<std::chrono::duration<double,std::ratio<1>>>
            (end-start).count();
    

    Note that in real code you should avoid using .count() to escape the strong typing provided by chrono::duration until you absolutely must.

    auto total_duration = end - start;
    auto seconds = std::chrono::duration_cast<std::chrono::seconds>(total_duration);
    auto milli = std::chrono::duration_cast<std::chrono::milliseconds>(total_duration - seconds);
    
    std::cout << seconds.count() << "s " << milli.count() << "ms\n";
    

1) I'm fairly certain the highest resolution you can get is to use std::chrono::high_resolution_clock and then don't do any duration casting:

int elapsed_ticks = (end-start).count();

2) Change the argument of duration_cast to something like nanoseconds:

int elapsed_seconds = std::chrono::duration_cast<std::chrono::nanoseconds>
                             (end-start).count();
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!