Correct way of portably timing code using C++11

前端 未结 1 1038
滥情空心
滥情空心 2020-12-16 03:55

I\'m in the midst of writing some timing code for a part of a program that has a low latency requirement.

Looking at whats available in the std::chrono library, I\'m

相关标签:
1条回答
  • 2020-12-16 04:39

    Use steady_clock. On all implementations its precision is nanoseconds. You can check this yourself for your platform by printing out steady_clock::period::num and steady_clock::period::den.

    Now that doesn't mean that it will actually measure nanosecond precision. But platforms do their best. For me, two consecutive calls to steady_clock (with optimizations enabled) will report times on the order of 100ns apart.

    #include "chrono_io.h"
    #include <chrono>
    #include <iostream>
    
    int
    main()
    {
        using namespace std::chrono;
        using namespace date;
        auto t0 = steady_clock::now();
        auto t1 = steady_clock::now();
        auto t2 = steady_clock::now();
        auto t3 = steady_clock::now();
        std::cout << t1-t0 << '\n';
        std::cout << t2-t1 << '\n';
        std::cout << t3-t2 << '\n';
    }
    

    The above example uses this free, open-source, header-only library only for convenience of formatting the duration. You can format things yourself (I'm lazy). For me this just output:

    287ns
    116ns
    75ns
    

    YMMV.

    0 讨论(0)
提交回复
热议问题