-1

more specifically can you please explain the working of following lines:

clock_t delay = secs * CLOCKS_PER_SEC;
clock_t start = clock() ;
while ( clock() - start < delay )

and the significance of semicolon in the next line.

#include<iostream>
#include<ctime>

int main () {
   
    using namespace std;
    
    cout << "Enter the delay time in sec: ";
    
    float secs;

    cin >> secs;

    clock_t delay = secs * CLOCKS_PER_SEC;

    cout << "starting \a\n" ;

    clock_t start = clock() ;

    while (clock() - start < delay )
         ;

    cout << "dont \a\n" ;
   
    return 0;

}
tadman
  • 208,517
  • 23
  • 234
  • 262
  • 1
    See [implement time delay in c](https://stackoverflow.com/questions/3930363/implement-time-delay-in-c) and in particular [this answer](https://stackoverflow.com/a/17930818). – dxiv Feb 09 '21 at 04:27
  • 1
    This thing is good at making your CPU fans spin up and your system start to really chug. It's not the way to do a simple delay. Consider tools like `sleep()` or [`sleep_for`](https://en.cppreference.com/w/cpp/thread/sleep_for). – tadman Feb 09 '21 at 04:39
  • If on Linux, read about [poll(2)](https://man7.org/linux/man-pages/man2/poll.2.html) and [time(7)](https://man7.org/linux/man-pages/man7/time.7.html)... – Basile Starynkevitch Feb 09 '21 at 04:45
  • 1
    `while (clock() - start < delay )` will consume 100% CPU. Never use it and just sleep instead – phuclv Feb 09 '21 at 04:45

1 Answers1

1

Overall, this program takes your delay in seconds, and prints output after waiting for the specified time. Now lets break each statement:

clock_t delay = secs * CLOCKS_PER_SEC;

you can think this line as converting your input delay (which is in seconds), to the unit that c++ clock library uses (clock_t). Generally CLOCKS_PER_SEC is equal to 1,000,000.

clock_t start = clock() ;

This line returns the current processor time, in clock_t units.

while (clock() - start < delay ) ;

represent an empty while loop, to wait until the current time - start time (The time difference) becomes greater than delay.

An empty while loop can also be written as

while(condition) {}
algoBoy
  • 13
  • 3