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.
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.
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.
Use some built-in sleep function, that does not use processor cycles to "wait", like sleep
from unistd.h
.
timer_func()
and printwow()
call each other forever. You'll eventually get a stack overflow.
because the loop
while (clock() < endwait) {}
cpu has to check the value of clock() all the time, use sleep() instead of your own code.
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.
精彩评论