我想每秒对从 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;
}
关于c++ - C++中的精确采样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39987806/