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

标签 c++ sampling c++-chrono

我想每秒对从 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/

相关文章:

python-3.x - 如何在Python3中随机生成未观察到的数据

c++ - 返回时调用函数的方法

php - 为 PHP 构建 Saxon/C 时出错

android - Mediarecorder 设置参数失败 (setAudioSamplingRate)

android - 使用RandomAccessFile直接从文件读取时,音频样本中的变化?

C++ std::chrono 在它自己的例子中给出了错误的输出

c++ - 使用 C++ 在多线程应用程序中测量全局时间(挂钟)的最快方法

c++ - 稳定时钟如何与有限位时间表示交互?

C++ OpenGL 从文件渲染简单的 OBJ

c++ - dlopen 期间 undefined symbol