Creating a millisecond delay w/in a loop?

May 23, 2010 at 3:18pm
To create an "active" delay within a loop, I use something like:

1
2
3
if (currentime-startime>1)
      c++;
      time(&startime);


And this will allow something (within a loop) to happen every real-time second.
Does anyone know how to do this with milliseconds (in such a way that the loop stays active)? Sleep(xxxx) won't work because its freezes the entire program.

I need something like:
if (currentime-startime>.5)

Thanks Guys!!
May 23, 2010 at 3:29pm
What do you mean? You want the program to do something once every 0.5 seconds (500 msec)?

Does it need to do anything in between?
May 23, 2010 at 3:36pm
For linux man 3 gettimeofday but it is expensive.
May 23, 2010 at 5:34pm
I'm looking to have a "timer" within a loop (one that will not stop the loop) that counts down by tenths of a second. I need for the loop to keep runing so that other actions can take place while the timer is active. In the code above, this is acheived, but not by "tenths" of a second. The smallest increment of time I can figure out is 1 second.
(Oh: and I'm using Visual Studio C++)



Last edited on May 23, 2010 at 5:34pm
May 23, 2010 at 5:59pm
Oh, I think I see what you mean.
Something like this?
1
2
3
4
5
6
7
8
9
10
11
#include <ctime>

clock_t t0=clock(),
    last=t0;
while (t1<t0){
    clock_t now=clock();
    if (now!=last && !((now-t0)%CLOCKS_PER_SEC)){
        //do stuff
        last=now;
    }
}
CLOCKS_PER_SEC is usually at least 1000.
May 24, 2010 at 12:19pm
Search msdn for high precision timers. Windows has quite a few (Don't ask me why).
Topic archived. No new replies allowed.