Newbie clock thing

Started by
3 comments, last by doynax 18 years, 3 months ago
I have a problem on C++. I want to "refresh" a function after 30 sec. I found this time function: --------------------------------- do { end=clock(); } while ((end-start)/CLK_TCK<30); ---------------------------------- that function should run 30 sec; Bu my function is: ------------------------------------- status() { cout<<money; cout<<xp; cout<<citizens; } -------------------------------------- So what I want is that status(); to refresh after 30 sec; (will display money,xp,citizens for 30sec and after that time should draw again same thing) I've tried to implemet the time function over my function bu I dont really know how. Sorry for this dumb question but I'm a newbie. Thanks
Advertisement
now = time_in_seconds( );while( now - last_time > 30 ) {  call_function( );  last_time += 30;}
That while loop will "do nothing" for 30 seconds, yes - while consuming all the CPU power to keep asking what time it is :) What you want to do is leave your refresh() function as is, and in a main "game loop", call it when an appropriate amount of time has elapsed.

int main() {  int start = clock();  while (gameShouldRun) {    doSomethingUseful();    sleep(1); // play nice with other processes    if ((clock() - start) / CLK_TCK < 30) {      // 30 seconds have elapsed, so we call the special update function      status();      // and "reset" the timer.      start = clock();    }  }}
Thanks a lot ToohrVyk and Zahlman. I should update my code
Bye
Quote:Original post by Zahlman
That while loop will "do nothing" for 30 seconds, yes - while consuming all the CPU power to keep asking what time it is :) What you want to do is leave your refresh() function as is, and in a main "game loop", call it when an appropriate amount of time has elapsed.
In this case you really do need the delay loop however, since clock often measures the process' elapsed cpu time.
So it's probably a better idea to use time() instead of clock(), and delay with a function like Unix's sleep() or Window's Sleep().

This topic is closed to new replies.

Advertisement