c++ - 减慢终端上的 C++ 输出

标签 c++ ascii ascii-art

我编写了一个模拟生命游戏的程序。基本上,世界是由 bool 的二维 std::vector 实现的。如果 bool 为 true,则细胞存活,如果为 false,则细胞死亡。程序的输出是每个时间步的系统,完全采用 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,您可以创建一个调度计时器源,以指定的频率调用您的绘制函数。

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 reference

关于c++ - 减慢终端上的 C++ 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12078119/

相关文章:

c++ - 在cpp中创建数组

C++ 执行脚本 Aprog 命令未找到

java - 使用任何开源代码或工具将大型机二进制文件转换为 ASCII

python - 由字母组成的字母

HTML 注释生成器

c++ - 打印心形,里面有文字

c++ - 独立源文件中的 SFINAE 模板特化

c++ - typeid/type_info 奇怪的行为

python - 如何使用 Python 将文件格式从 Unicode 转换为 ASCII?

python - 为什么 ByteArray() 组合数组值? (Python)