<ctime> sample program

Could anyone explain this sample program to me. I can't see how the while loop works, in this instance. I don't know what clock_t start = clock(); means, either.. thx


#include <iostream>
#include <ctime>
using namespace std;

int main()
{
cout << "Enter the delay time, in seconds: ";
float secs;
cin >> secs;
clock_t delay = secs * CLOCKS_PER_SEC;
cout << "starting\a\n";
clock_t start = clock();
while (clock() - start < delay )
;
cout << "done \a\n";
return 0;
}
clock_t start = clock () says basically "create a clock object named start and set it to the number of ticks that have passed since the program launched".

The while loop is a cross-platform pause. It keeps looping doing NOTHING until clock() - the time it took for the computer to process the input and initialize the variables has elapsed.

-Albatross
thx


I still don't get what Clock() - start is.
What I'm saying is, if "start" is equal to Clock(), then why not just put Clock() - Clock() inside the loop?

Because you may need a greater amount of control over your application later, and/or it's good practice to use a variable for these situations.
What I'm saying is, if "start" is equal to Clock(), then why not just put Clock() - Clock()
clock() gives a different value each time you call it, because, as Albatross said, it returns the number of ticks passed from the beginning of your program to the moment you call it. Thus, clock()-clock() would be a very small number (it would be the number of ticks between two clock() calls) and if delay is too big
while (clock() - clock() < delay );
could be a never ending loop...

EDIT: In fact, clock()-clock() would be a negative number, so
while (clock() - clock() < delay );
is always a never ending loop, when delay is positive...
Last edited on
I THINK, I'm starting to get it.. :)

What is the purpose of the semi colon after the loop ?
nevermind I get it thx everyone
Topic archived. No new replies allowed.