Jump to content

Timer in C++


jaydnul

Recommended Posts

All I need is to run a certain section of my code (that loops forever) for a certain amount of time, about 10 seconds. The obvious problem is when it gets to that section, it loops forever and doesn't move on. Is there a function that will allow me to run a given chunk for a given amount of time?

 

Thanks

Link to comment
Share on other sites

Windows OS has Sleep() function.

http://msdn.microsoft.com/en-us/library/windows/desktop/ms686298%28v=vs.85%29.aspx

 

For portable C/C++ you can use time() and/or clock() functions in loop and looking for certain increase of result.

But this way CPU will be 100% busy while waiting.

Sleep() will put thread to sleep taking 0% CPU.

 

Edited by Sensei
Link to comment
Share on other sites

Of course there is runs for 10 seconds.

#include <iostream>
#include <string>
#include <stdio.h>
#include <time.h>

int main() {

    int b=time(0)+10;
    while(b>time(0))
    {
            std::cout << time(0) << std::endl;
    }
}
Edited by fiveworlds
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.