繁体   English   中英

Raspberry Pi上的C ++ chrono库

[英]C++ chrono library on Raspberry Pi

在Raspberry Pi 2上,我需要定期调用一个php文件,通常每100毫秒。 我发现这个c ++代码看起来像我需要的东西,它的测试版本在Windows上使用CodeBlock进行编译和运行。 我使用本指南更新了来自jessie的C ++库的喘息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()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);
  ...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM