Raspberry Pi 上的 C++ 计时库

C++ chrono library on Raspberry Pi

在 Raspberry Pi 2 上,我需要定期调用 php 文件,通常每 100 毫秒调用一次。我发现 this c++ code which looks like it does what I need and a test version of it compiles and runs fine using CodeBlock on Windows. I've updated the wheezy RPi with C++ libraries from jessie using this guide,使用 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 literal 来简化 period:

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

或者,更类似于您找到的答案,而不是使用表示 100 毫秒的变量,您可以定义一个表示该持续时间的类型,然后添加该类型的单位(而不是 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);
  ...
}