簡體   English   中英

用c ++進行准確采樣

[英]accurate sampling in c++

我想對每秒從gpio獲得的值進行4000次采樣,目前我正在執行類似的操作:

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;
}

但是根據參考,sleep_for可以保證至少等待指定的時間。

如何讓系統等待確切的時間,或者至少達到最佳的准確性? 我如何確定系統的時間分辨率?

我認為您可能可以實現的最好方法是使用絕對定時以避免漂移。

像這樣:

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;
}

我會使用boost :: asio :: deadline_timer

#include <vector>

#define BOOST_ERROR_CODE_HEADER_ONLY 1
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

std::vector<int> sample_a_chunk(unsigned int rate, unsigned int block_size_in_seconds) {
  std::vector<int> data;
  const unsigned int times = rate * block_size_in_seconds;
  auto expiration_time = boost::posix_time::microsec_clock::local_time();
  const auto delay = boost::posix_time::microseconds(1000000/rate);
  boost::asio::io_service io;
  boost::asio::deadline_timer t(io);

  for (unsigned int j=0; j < times; j++) {
    expiration_time += delay;
    data.emplace_back(/* read the value from the gpio */);
    t.expires_at(expiration_time);
    t.wait();
  }
  return data;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM