luacoder
luacoder

Reputation: 209

Simple C app using 50% cpu

I have a simple C app that uses constant 50%. I don't know why but I like to minimize it as much as possible.

#include <stdlib.h>
#include <stdio.h>
#include <time.h>

void Wait(int seconds)
{
clock_t endwait;
endwait = clock () + seconds * CLK_TCK ;
while (clock() < endwait) {}
}

void main()
{
printf ("program running.\n");
/* Wait( 4 ); */
printf( "Done Waiting!\n" );
printwow();
/* exit(0); */
}

timer_func (void)
{
Wait( 4 );
printwow();
}

printwow()
{
printf ("Say hello");
timer_func();
}

I guess it must be the timer of course. But I don't know that for sure.

Thanks.

Upvotes: 1

Views: 361

Answers (6)

jarmod
jarmod

Reputation: 78573

If you want your code to sleep for 4 seconds then you can use sleep(4) to do that and it will almost certainly not consume CPU like your wait() function does. Note that sleep(4) will block execution of the remainder of your single-threaded program and if you do not want that then you will need something more sophisticated, but I suspect sleep(4) will suffice here.

Also, your code will eventually exhaust the stack because printwow() calls timer_func() which calls printwow() which calls timer_func() etc. etc. ad infinitum in a recursive loop. You need to fix this, probably by using a for/while loop rather than recursion.

Upvotes: 1

Griwes
Griwes

Reputation: 9031

Use some built-in sleep function, that does not use processor cycles to "wait", like sleep from unistd.h.

Upvotes: 3

Matt K
Matt K

Reputation: 13832

timer_func() and printwow() call each other forever. You'll eventually get a stack overflow.

Upvotes: 2

lostyzd
lostyzd

Reputation: 4523

because the loop

while (clock() < endwait) {}

cpu has to check the value of clock() all the time, use sleep() instead of your own code.

Upvotes: 1

Simon Nickerson
Simon Nickerson

Reputation: 43159

Your loop:

while (clock() < endwait) {}

is busy-waiting. You are basically having the following conversation with the CPU.

"Are we there yet?" "No."

"Are we there yet?" "No."

"Are we there yet?" "No."

(repeat several gazillion times)

"Are we there yet?" "Yes."

You are better off using a function like sleep() which tells the CPU to tell you when it's ready.

Upvotes: 21

Fred Larson
Fred Larson

Reputation: 62053

Yes, it's your tight loop in Wait(). You probably have a dual-core machine, so you're using 100% of one core. Use sleep() instead.

Upvotes: 4

Related Questions