Dav*_*veH 3 c++ c++-chrono raspberry-pi c++14
在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;
}
Run Code Online (Sandbox Code Playgroud)
我的问题可能与其中一个库或代码中的其他内容有关吗?我甚至不确定这是实现我想要的最佳方式,因为运行时的代码看起来像是在循环中占用了处理器.
问题是输出是由stdio库缓冲的,您需要刷新输出流以使其立即显示:
std::cout << "OK " << std::flush;
Run Code Online (Sandbox Code Playgroud)
您的解决方案效率非常低,因为它执行繁忙的循环,不断重新检查间隔之间的系统时间.
我会使用单个调用来获取时间,然后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;
}
}
Run Code Online (Sandbox Code Playgroud)
由于您使用的是C++ 14,因此您还可以使用operator""ms文字来简化以下声明period:
using namespace std::literals::chrono_literals;
auto period = 100ms;
Run Code Online (Sandbox Code Playgroud)
或者,更类似于您找到的答案,而不是使用表示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);
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
926 次 |
| 最近记录: |