我编写了一个模拟生命游戏的程序。基本上,世界是由 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();
关于c++ - 减慢终端上的 C++ 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12078119/