Simple C app using 50% cpu

后端 未结 6 1665
不思量自难忘°
不思量自难忘° 2021-01-25 03:31

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 
#include          


        
相关标签:
6条回答
  • 2021-01-25 03:40

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

    0 讨论(0)
  • 2021-01-25 03:50

    because the loop

    while (clock() < endwait) {}
    

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

    0 讨论(0)
  • 2021-01-25 03:52

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

    0 讨论(0)
  • 2021-01-25 03:55

    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.

    0 讨论(0)
  • 2021-01-25 03:57

    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.

    0 讨论(0)
  • 2021-01-25 04:02

    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.

    0 讨论(0)
提交回复
热议问题