【发布时间】:2017-02-20 14:50:18
【问题描述】:
我想以每秒 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 保证等待至少指定的时间量。
我怎样才能让我的系统等待准确的时间,或者至少达到可能的最佳准确性? 如何确定系统的时间分辨率?
【问题讨论】:
-
您需要使用操作系统服务来完成您的要求。
-
没有办法睡一个“确切”的时间。这不是计算机的工作方式。即使是 RTOS 也不能保证准确的睡眠。当您不知道有多好就足够好时,为什么不花时间尝试使其“更好”之前,看看您已经拥有的东西有多好。
-
操作系统shmoperating system。你需要准确的时间,你需要一个确定性的系统,它用线程和中断写出任何东西。争取足够好的时间。确保你的定时器分辨率是你需要的 5-10 倍,并且上下文切换延迟足够低,以确保你永远不会过度睡眠,足以照顾。
-
如果您想避免时间漂移,请使用绝对计时 (
wait_until),这可能很有用:stackoverflow.com/questions/37240834/… -
高效的 4 kHz 采样?听起来像是声卡最好处理的任务。它们通常可以缓冲大量读数,几乎没有抖动,并且每个样本不需要太多 CPU。