gpt4 book ai didi

c++ - c++中的精确采样

转载 作者:搜寻专家 更新时间:2023-10-31 01:34:13 24 4
gpt4 key购买 nike

我想以每秒 4000 次的频率对从 gpio 获得的值进行采样,目前我正在做类似的事情:

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

关于c++ - c++中的精确采样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39987806/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com