Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

accurate sampling in c++

I want to sample values I get from a gpio 4000 times per second, currently I do something like that:

std::vector<int> sample_a_chunk(unsigned int rate, unsigned int block_size_in_seconds) {
    std::vector<std::int> data;
    constexpr unsigned int times = rate * block_size_in_seconds;
    constexpr unsigned int delay = 1000000 / rate; // microseconds
    for (int j=0; j<times; j++) {
      data.emplace_back(/* read the value from the gpio */);
      std::this_thread::sleep_for(std::chrono::microseconds(delay));
    }
    return data;
}

yet according to the reference sleep_for is guaranteed to wait for at least the specified amount of time.

How can I have my system wait for the exact amount of time, or at least achieve the best possible accuracy? How can I be sure of the time resolution of my system?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I think the best you can probably achieve is to use absolute timing so as to avoid drift.

Something like this:

std::vector<int> sample_a_chunk(unsigned int rate,
    unsigned int block_size_in_seconds)
{
    using clock = std::chrono::steady_clock;

    std::vector<int> data;

    const auto times = rate * block_size_in_seconds;
    const auto delay = std::chrono::microseconds{1000000 / rate};

    auto next_sample = clock::now() + delay;

    for(int j = 0; j < times; j++)
    {
        data.emplace_back(/* read the value from the gpio */);

        std::this_thread::sleep_until(next_sample);

        next_sample += delay; // don't refer back to clock, stay absolute
    }
    return data;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...