正在减慢端子上的C++输出

Slowing C++ output on terminal

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

我写了一个程序,模拟生命游戏。基本上,世界是由bool的二维std::向量实现的。如果bool为真,则细胞是活的,如果为假,则细胞死亡。程序的输出是每个时间步长的系统,完全采用ASCII代码:

[ ][0][ ]
[ ][ ][0]
[0][0][0]

问题是程序运行得很快,而且每次打印步骤都太快:我看不出系统是如何发展的。有没有一些技巧可以降低输出速度(或者直接降低程序速度)?

编辑:我使用的是Mac OS X 10.7。我的编译器是GCC 4.7。

您可以使用标准C++(C++11):

#include <thread>
#include <chrono>
#include <iostream>
int main() {
    while (true) {
        // draw loop
        std::this_thread::sleep_for(std::chrono::milliseconds(20));
    }
}

或者,您可以使用一个库来指定调用绘制函数的间隔。OS X具有Grand Central Dispatch(又称libdispatch)。使用GCD,您可以创建一个调度定时器源,以指定的频率调用draw函数。

dispatch_source_t timer = dispatch_source_create(
    DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW,
    duration_cast<nanoseconds>(milliseconds(20)).count(),
    duration_cast<nanoseconds>(milliseconds( 5)).count());
// the API is defined to use nanoseconds, but I'd rather work in milliseconds
// so I use std::chrono to do the conversion above
dispatch_source_set_event_handler(timer,
    []{ your_draw_function(); });
// I'm not sure if GCC 4.7 actually supports converting C++11 lambdas to
// Apple's C blocks, or if it even supports blocks. Clang supports this.
dispatch_resume(timer);
dispatch_main();

libdispatch引用

无论你使用什么系统,它都会有某种睡眠函数,你可以调用它,它会暂停你的程序一段指定的时间。你没有具体说明你使用的操作系统,所以我不能给出确切的细节,但这听起来像是你正在寻找的方法。

如果在绘制图像的每次更新后调用睡眠一段时间,则程序将在恢复并绘制下一次更新之前睡眠该时间。这应该会让你有机会真正看到的变化

如果你想要更高分辨率的睡眠时间,你可以查看nanosleepusleep

1.您可以使用

int tmp; std::cin >> tmp;

程序会在之前要求您进一步了解。

2.你可以在一些计算中使用循环。像

double Tmp[1000000];
for( int i = 0; i < 1000000; i++ )
  Tmp[i] = i;
for( int i = 0; i < 1000000; i++ )
  Tmp[i] = sin(sin(sin(Tmp[i])));

3.您可以查看哪些延迟功能可供您使用。示例是中的"睡眠(nSconds)"

4.您可以保存并验证您的系统时间。类似:

 while (time() < time_end){};