c - Simple <Time.h> program takes large amount CPU -


i trying familiarize myself c time.h library writing simple in vs. following code prints value of x added every 2 seconds:

int main() {     time_t start = time(null);     time_t clock = time(null);     time_t clocktemp = time(null); //temporary clock      int x = 1;      //program continue minute (60 sec)     while (clock <= start + 58) {         clocktemp = time(null);         if (clocktemp >= clock + 2) { //if 2 seconds has passed             clock = clocktemp;             x = add(x);             printf("%d @ %d\n", x, timediff(start, clock));         }     } }  int timediff(int start, int at) {     return @ - start; } 

my concern amount of cpu program takes, 22%. figure problem stems constant updating of clocktemp (just below while statement), i'm not sure how fix issue. possible visual studio problem, or there special way check time?

solution

the code needed sleep function wouldn't need run constantly. added sleep #include <windows.h> , put sleep (2000) //2 second sleep @ end of while

while (clock <= start + 58) { ... sleep(2000); }

the problem not in way checking current time. problem there nothing limit frequency loop runs. program continues execute statements can, , eats ton of processor time. (in absence of other programs, on single-threaded cpu, use 100% of processor time.)

you need add "sleep" method inside loop, indicate processor can stop processing program short period of time. there many ways this; this question has examples.


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -