计时器
计时器是需要引入头文件”ctime”,通过函数 clock()
来获得时间
需要使用CLOCKS_PER_SEC这个玩意来转换
#include <iostream>
#include <ctime>
using namespace std;
int main() {
clock_t t1, t2;
long n = 1000000;
t1 = clock();
while(n--);
t2 = clock();
cout << t1 << "," << t2 << endl;
}
// 输出
延时计时器
如果调用系统 sleep
函数,那么程序被挂起,不能进行别的操作;如果使用计时器进行延时,只是每个循环进行读系统时间,从而其他操作还可以进行
使用小球移动的代码
#include <windows.h>
#include <iostream>
using namespace std;
void gotoxy(int x, int y)
{
HANDLE h;
COORD c;
c.X = x;
c.Y = y;
h = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(h, c);
}
void move(int x0, int y0)
{
int x = x0, y = y0;
while (true)
{
gotoxy(x, y);
cout << "+";
Sleep(10);
gotoxy(x, y);
cout << " ";
++x;
if (x >= 100) x = 0; // 等价于 x = x % 100;
}
}
int main()
{
move(0, 10);
return 0;
}
只关注 move()
函数,下面进行修改
void move(int x0, int y0)
{
int x = x0, y = y0;
clock_t t;
t = clock();
while (true)
{
gotoxy(x, y);
cout << "+";
if(clock() - t > 10) {
gotoxy(x, y);
cout << " ";
++x;
if (x >= 100) x = 0; // 等价于 x = x % 100;
t = clock();
}
}
}
但是这样的结果,小球会产生闪烁 —- 原因在于不管到没到时间,都执行 goto
画小球。
改进的思想就是如果没有擦除小球,就不要重新绘制小球。通过加入标识flag修改
void move(int x0, int y0)
{
int x = x0, y = y0;
clock_t t;
t = clock();
bool flag = true;
while (true)
{
if (flag == true) {
gotoxy(x, y);
cout << "+";
flag = false;
}
if(clock() - t > 10) {
gotoxy(x, y);
cout << " ";
flag = true;
++x;
if (x >= 100) x = 0; // 等价于 x = x % 100;
t = clock();
}
}
}
多线程
自己写多线程
这里的多线程是受到操作系统的限制的,windows分配给这个程序的最小时间间隔是10ms
在小球移动程序的基础上,通过多线程和计时器,实现多个小球同时移动
void move(int x0, int y0)
{
int x1 = x0, y1 = y0;
int x2 = x0, y2 = y0 + 10;
clock_t t1, t2;
t2 = t1 = clock();
bool flag1 = true, flag2 = true;
while (true)
{
if (flag1 == true) {
gotoxy(x1, y1);
cout << "+";
flag1 = false;
}
if(clock() - t1 > 10) {
gotoxy(x1, y1);
cout << " ";
flag1 = true;
++x1;
if (x1 >= 100) x1 = 0; // 等价于 x = x % 100;
}
if (flag2 == true) {
gotoxy(x2, y2);
cout << "+";
flag2 = false;
}
if(clock() - t2 > 20) { // 第二个小球运动慢一点
gotoxy(x2, y2);
cout << " ";
flag2 = true;
++x2;
if (x2 >= 100) x2 = 0; // 等价于 x = x % 100;
}
}
}