计时器

计时器是需要引入头文件”ctime”,通过函数 clock() 来获得时间

需要使用CLOCKS_PER_SEC这个玩意来转换

image.png

  1. #include <iostream>
  2. #include <ctime>
  3. using namespace std;
  4. int main() {
  5. clock_t t1, t2;
  6. long n = 1000000;
  7. t1 = clock();
  8. while(n--);
  9. t2 = clock();
  10. cout << t1 << "," << t2 << endl;
  11. }
  12. // 输出

延时计时器

如果调用系统 sleep 函数,那么程序被挂起,不能进行别的操作;如果使用计时器进行延时,只是每个循环进行读系统时间,从而其他操作还可以进行
使用小球移动的代码

  1. #include <windows.h>
  2. #include <iostream>
  3. using namespace std;
  4. void gotoxy(int x, int y)
  5. {
  6. HANDLE h;
  7. COORD c;
  8. c.X = x;
  9. c.Y = y;
  10. h = GetStdHandle(STD_OUTPUT_HANDLE);
  11. SetConsoleCursorPosition(h, c);
  12. }
  13. void move(int x0, int y0)
  14. {
  15. int x = x0, y = y0;
  16. while (true)
  17. {
  18. gotoxy(x, y);
  19. cout << "+";
  20. Sleep(10);
  21. gotoxy(x, y);
  22. cout << " ";
  23. ++x;
  24. if (x >= 100) x = 0; // 等价于 x = x % 100;
  25. }
  26. }
  27. int main()
  28. {
  29. move(0, 10);
  30. return 0;
  31. }

只关注 move() 函数,下面进行修改

  1. void move(int x0, int y0)
  2. {
  3. int x = x0, y = y0;
  4. clock_t t;
  5. t = clock();
  6. while (true)
  7. {
  8. gotoxy(x, y);
  9. cout << "+";
  10. if(clock() - t > 10) {
  11. gotoxy(x, y);
  12. cout << " ";
  13. ++x;
  14. if (x >= 100) x = 0; // 等价于 x = x % 100;
  15. t = clock();
  16. }
  17. }
  18. }

但是这样的结果,小球会产生闪烁 —- 原因在于不管到没到时间,都执行 goto 画小球。
改进的思想就是如果没有擦除小球,就不要重新绘制小球。通过加入标识flag修改

  1. void move(int x0, int y0)
  2. {
  3. int x = x0, y = y0;
  4. clock_t t;
  5. t = clock();
  6. bool flag = true;
  7. while (true)
  8. {
  9. if (flag == true) {
  10. gotoxy(x, y);
  11. cout << "+";
  12. flag = false;
  13. }
  14. if(clock() - t > 10) {
  15. gotoxy(x, y);
  16. cout << " ";
  17. flag = true;
  18. ++x;
  19. if (x >= 100) x = 0; // 等价于 x = x % 100;
  20. t = clock();
  21. }
  22. }
  23. }

多线程

自己写多线程

这里的多线程是受到操作系统的限制的,windows分配给这个程序的最小时间间隔是10ms
image.png
在小球移动程序的基础上,通过多线程和计时器,实现多个小球同时移动

  1. void move(int x0, int y0)
  2. {
  3. int x1 = x0, y1 = y0;
  4. int x2 = x0, y2 = y0 + 10;
  5. clock_t t1, t2;
  6. t2 = t1 = clock();
  7. bool flag1 = true, flag2 = true;
  8. while (true)
  9. {
  10. if (flag1 == true) {
  11. gotoxy(x1, y1);
  12. cout << "+";
  13. flag1 = false;
  14. }
  15. if(clock() - t1 > 10) {
  16. gotoxy(x1, y1);
  17. cout << " ";
  18. flag1 = true;
  19. ++x1;
  20. if (x1 >= 100) x1 = 0; // 等价于 x = x % 100;
  21. }
  22. if (flag2 == true) {
  23. gotoxy(x2, y2);
  24. cout << "+";
  25. flag2 = false;
  26. }
  27. if(clock() - t2 > 20) { // 第二个小球运动慢一点
  28. gotoxy(x2, y2);
  29. cout << " ";
  30. flag2 = true;
  31. ++x2;
  32. if (x2 >= 100) x2 = 0; // 等价于 x = x % 100;
  33. }
  34. }
  35. }

类实现