C++11 C++;11时钟高分辨率时钟在忙环路中的稳定性?
下面的代码利用C++11C++11 C++;11时钟高分辨率时钟在忙环路中的稳定性?,c++11,chrono,C++11,Chrono,下面的代码利用C++11std::chrono来累积两个后续滴答声之间的增量时间,并输出每秒间隔累积的滴答声数以及该1秒间隔内的平均滴答声时间 然而,在我的Xcode环境下,当我运行代码(在调试中)时,输出之间的间隔似乎远大于1秒(可能至少间隔2秒)——时间线似乎比实际时间线延长了 如果取消对sleep行的注释,代码将显示正确的行为 谁能告诉我出了什么问题吗 #include <iostream> #include <chrono> #include <thread
std::chrono
来累积两个后续滴答声之间的增量时间,并输出每秒间隔累积的滴答声数以及该1秒间隔内的平均滴答声时间
然而,在我的Xcode环境下,当我运行代码(在调试中)时,输出之间的间隔似乎远大于1秒(可能至少间隔2秒)——时间线似乎比实际时间线延长了
如果取消对sleep行的注释,代码将显示正确的行为
谁能告诉我出了什么问题吗
#include <iostream>
#include <chrono>
#include <thread>
std::chrono::high_resolution_clock::time_point then{};
double accumulator = 0.0;
size_t count = 0;
void Tick()
{
if (then != std::chrono::high_resolution_clock::time_point{}) {
auto delta = std::chrono::duration<double>(std::chrono::high_resolution_clock::now() - then).count();
accumulator += delta;
++count;
if (accumulator >= 1.0) {
std::cout << "count: " << count << " | average delta: " << 1.0 / count << std::endl;
accumulator = 0.0;
count = 0;
}
} else {
std::cout << "###" << std::endl;
}
then = std::chrono::high_resolution_clock::now();
}
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
while (true) {
Tick();
// uncomment the following line exhibits the correct behavior
//std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
return 0;
}
#包括
#包括
#包括
std::chrono::高分辨率时钟::时间点然后{};
双累加器=0.0;
大小\u t计数=0;
空勾()
{
if(then!=std::chrono::高分辨率时钟::时间点{}){
auto delta=std::chrono::duration(std::chrono::high_resolution_clock::now()-then).count();
累加器+=增量;
++计数;
如果(累加器>=1.0){
std::cout因此,经过一些挖掘,发现delta
计算逻辑以及现在的使用方式存在缺陷。有几点:
现在
只应在进入勾选功能后记录,并在整个范围内使用
- 原始代码基本上只测量整个时间线的子部分,如
delta
,这就是为什么部分delta
的累积小于实际经过的时间,因此时间似乎比实际时间线延长得多
工作代码如下所示:
#include <iostream>
#include <chrono>
#include <thread>
std::chrono::high_resolution_clock::time_point then{};
double accumulator = 0.0;
size_t count = 0;
void Tick()
{
auto now = std::chrono::high_resolution_clock::now(); // the time point of this tick
if (then != std::chrono::high_resolution_clock::time_point{}) {
auto delta = std::chrono::duration<double>(now - then).count(); // should use the recorded time point 'now'
accumulator += delta;
++count;
if (accumulator >= 1.0) {
std::cout << "count: " << count << " | average delta: " << 1.0 / count << std::endl;
accumulator = 0.0;
count = 0;
}
} else {
std::cout << "###" << std::endl;
}
then = now; // should use the recorded time point as this tick time
}
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
while (true) {
Tick();
// other processing
//std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
return 0;
}
#包括
#包括
#包括
std::chrono::高分辨率时钟::时间点然后{};
双累加器=0.0;
大小\u t计数=0;
空勾()
{
auto now=std::chrono::high_resolution_clock::now();//此刻度的时间点
if(then!=std::chrono::高分辨率时钟::时间点{}){
auto delta=std::chrono::duration(now-then).count();//应使用记录的时间点'now'
累加器+=增量;
++计数;
如果(累加器>=1.0){
标准::cout