用c ++进行准确采样 [英] accurate sampling in c++
本文介绍了用c ++进行准确采样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想对每秒从gpio中获得的值进行4000次采样,目前我正在执行类似的操作:
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;
}
根据参考sleep_for,仍然可以保证至少指定时间的等待时间.
yet according to the reference sleep_for is guaranteed to wait for at least the specified amount of time.
我如何让我的系统等待 exact 的时间,或者至少达到最佳精度?如何确定系统的时间分辨率?
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?
推荐答案
我认为您可能可以实现的最佳效果是使用绝对计时以避免漂移.
I think the best you can probably achieve is to use absolute timing so as to avoid drift.
类似这样的东西:
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;
}
这篇关于用c ++进行准确采样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文