正在减慢端子上的C++输出
Slowing C++ output on terminal
我写了一个程序,模拟生命游戏。基本上,世界是由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引用
无论你使用什么系统,它都会有某种睡眠函数,你可以调用它,它会暂停你的程序一段指定的时间。你没有具体说明你使用的操作系统,所以我不能给出确切的细节,但这听起来像是你正在寻找的方法。
如果在绘制图像的每次更新后调用睡眠一段时间,则程序将在恢复并绘制下一次更新之前睡眠该时间。这应该会让你有机会真正看到的变化
如果你想要更高分辨率的睡眠时间,你可以查看nanosleep
和usleep
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){};
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 请解释"函数1(p1,p2,p3);"的输出
- C++:将控制台输出存储在宏中更好吗
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 为什么我的代码在输出中增加了93天
- 如何从void函数输出字符串
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- AES加密到解密未正确输出
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用C++程序合并排序没有得到正确的输出
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- C++格式化输出问题
- 将值从二维数组输出到文本文件
- 集合上的输出迭代器:assign和increment迭代器
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 为什么rk4.do_step不输出C++中的初始条件
- 输出没有重复元素的动态数组(收缩数组)C++
- 如何根据单词在文本中出现的概率输出单词