Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
340 views
in Technique[技术] by (71.8m points)

c++ - Correct way of portably timing code using C++11

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 finding it a bit difficult to write timing code that is portable.

  1. std::chrono::high_resolution_clock
  2. std::chrono::steady_clock
  3. std::chrono::system_clock

The system_clock is useless as it's not steady, the remaining two clocks are problematic.

The high_resolution_clock isn't necessarily stable on all platforms.

The steady_clock does not necessarily support fine-grain resolution time periods (eg: nano seconds)

For my purposes having a steady clock is the most important requirement and I can sort of get by with microsecond granularity.

My question is if one wanted to time code that could be running on different h/w architectures and OSes - what would be the best option?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 << '
';
    std::cout << t2-t1 << '
';
    std::cout << t3-t2 << '
';
}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...