我想从每秒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;
}