簡體   English   中英

在C ++中為進程設置時間限制

[英]Placing a time limit on a process in C++

我正在嘗試用C ++制作1分鍾的條紋動畫。 我使用Akki的TurboC ++ 7做到了這一點。 我似乎無法使clock()函數滿足我的需求。 我想要實現的是能夠為動畫/程序執行設置60秒的時間限制。 誰能告訴我這是怎么了?

#include <iostream.h>
#include <conio.h>
#include <dos.h>
#include <graphics.h>
#include <stdlib.h>
#include <time.h>

void main(){
     clock_t start, point;
     int gDriver = DETECT, gMode, errCode, tme;
     clrscr();
     initgraph(&gDriver, &gMode, "C:\\TC\\BGI");

 errCode = graphresult();

 if (errCode != grOk){
  cout << "Graphics error:\n" << grapherrormsg(errCode);
  cout << "\n\nPress any key to continue...";
  getch();
  exit(1);
 }

 setbkcolor(0);

 do{
  start = clock() / CLOCKS_PER_SEC;
  int x = 1, y = rand() % 480, r = rand() % 21;
  setcolor(rand() % 16);
  do{
       if(kbhit())
        break;
       circle(x, y, r);
       x++;
  } while (x != 639);

  x = rand() % 640, y = 1, r = rand() % 21;
  setcolor(rand() % 16);
  do{
       if(kbhit())
        break;
       circle(x, y, r);
       y++;
  } while (y != 479);

  x = 639, y = rand() % 480, r = rand() % 21;
  setcolor(rand() % 16);
  do{
       if (kbhit())
        break;
       circle(x, y, r);
       x--;
  } while (x != 1);

  x = rand() % 640, y = 479, r = rand() % 21;
  setcolor(rand() % 16);
  do{
       if (kbhit())
        break;
       circle(x, y, r);
       y--;
  } while (y != 1);
  point = clock() / CLOCKS_PER_SEC;
  if ((point - start) >= 10)
      break;
  else
       tme += point - start;
 } while (!kbhit());

 getch();
 closegraph();
}
point = clock() / CLOCKS_PER_SEC;
if ((point - start) >= 10)
    break;

在這里,您的時間限制為10 CPU秒,而不是所需的60秒。 另外,使用time()獲取實時時間,而不是CPU時間。

正如@rpattiso所評論的那樣,您應該查看行start = clock() / CLOCKS_PER_SEC; 應該放在do ... while循環之前或內部。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM