[try Beta version]
Not logged in

 
<ctime> sample program

May 2, 2010 at 2:26am
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;
}
May 2, 2010 at 2:32am
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
May 2, 2010 at 1:49pm
thx


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

May 2, 2010 at 3:00pm
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.
May 2, 2010 at 3:22pm
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 May 2, 2010 at 3:26pm
May 2, 2010 at 3:46pm
I THINK, I'm starting to get it.. :)

What is the purpose of the semi colon after the loop ?
May 2, 2010 at 4:45pm
nevermind I get it thx everyone
Topic archived. No new replies allowed.