C++树莓派上的计时库

C++ chrono library on Raspberry Pi

本文关键字:C++      更新时间:2023-10-16

在Raspberry Pi 2上,我需要定期调用一个php文件,通常每100ms调用一次。 我发现这个 c++ 代码看起来可以满足我的需要,并且它的测试版本使用 Windows 上的 CodeBlock 编译和运行良好。 我已经使用本指南使用 jessie 的 C++ 库更新了 wheezy RPi,使用 g++-4.9 -std=c++14 在 Pi 上编译了它,但我没有得到任何输出。 我对 Linux 和C++很陌生,所以任何帮助将不胜感激。 代码如下

#include <iostream>
#include <cstdlib>
#include <chrono>
using namespace std;
int main () {
    using frame_period = std::chrono::duration<long long, std::ratio<50, 100>>;
    auto prev = std::chrono::high_resolution_clock::now();
    auto current = prev;
    auto difference = current-prev;
    while(true)
    {
        while (difference < frame_period{1})
        {
            current = std::chrono::high_resolution_clock::now();
            difference = current-prev;
        }
        //cout << std::system("php run.php");
        std::cout << "OK ";
        using hr_duration = std::chrono::high_resolution_clock::duration;
        prev = std::chrono::time_point_cast<hr_duration>(prev + frame_period{1});
        difference = current-prev;
    }
return 0;
}

我的问题可能出在其中一个库还是代码中的其他内容? 我什至不确定这是实现我想要的最好方法,因为运行时的代码看起来像是将处理器捆绑在循环中。

问题是输出正在被 stdio 库缓冲,您需要刷新输出流以使其立即显示:

    std::cout << "OK " << std::flush;

您的解决方案效率非常低,因为它执行繁忙循环,不断重新检查间隔之间的系统时间。

我会使用单个调用来获取时间,然后this_thread::sleep_until()使程序阻塞,直到您要再次运行脚本:

#include <iostream>
#include <cstdio>
#include <chrono>
# include <thread>
int main()
{
  std::chrono::milliseconds period(100);
  auto next = std::chrono::high_resolution_clock::now() + period;
  while (true)
  {
    std::this_thread::sleep_until(next);
    next += period;
    // std::system("php run.php");
    std::cout << "OK " << std::flush;
  }
}

由于您使用的是 C++14,因此您还可以使用 operator""ms 文字来简化period的声明:

using namespace std::literals::chrono_literals;
auto period = 100ms;

或者,与您找到的答案更相似,您可以定义表示该持续时间的类型,而不是使用表示 100ms 的变量,然后将该类型的单位(而不是 100 个类型 milliseconds 的单位)添加到next值:

// a type that represents a duration of 1/10th of a second
using period = std::chrono::duration<long, std::ratio<1, 10>>;
auto next = std::chrono::high_resolution_clock::now() + period(1);
while (true)
{
  std::this_thread::sleep_until(next);
  next += period(1);
  ...
}
相关文章:
  • 没有找到相关文章