'Placing a time limit on a process in C++
I'm trying to make a 1-minute animation of stripes in C++. I made this with TurboC++7 by Akki. I can't seem to make the clock() function work to my needs. What I want achieve is to be able to set a 60-second time limit on the animation/program execution. Can anyone tell me what's wrong with this?
#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();
}
Solution 1:[1]
point = clock() / CLOCKS_PER_SEC;
if ((point - start) >= 10)
break;
Here your time limit is 10 CPU seconds, not 60 seconds as you required.
Also, use time() to get real time rather than CPU time.
As @rpattiso commented, you should review whether the line start = clock() / CLOCKS_PER_SEC; should be put before or inside the do ... while loop.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | timrau |
