3

I'm coding an script in C, which is going to check constantly an array of events, the idea is to check if the Date and time of certain event is equal to de current time and trigger something, i'm doing this with a while(1){}, but this approach causes a high CPU usage, do you have any suggestion of how can i do this with a lower CPU usage ?

  • 3
    Where do the events come from? – Doc Brown Sep 17 '14 at 15:58
  • Try adding a sleep of 1 millisecond at the end of the loop. – user1751547 Sep 17 '14 at 16:00
  • 3
    You should explain more about your "events", and you might consider poll(2) if these events come on file descriptors (as they should) – Basile Starynkevitch Sep 17 '14 at 16:13
  • @BasileStarynkevitch Its a home Automation project with a Raspberry Pi, the events are programmed task, like sending a signal to turn on a light at certain date and time. – David T Sep 17 '14 at 18:41
  • 1
    Please edit your question, and read Advanced Linux Programming – Basile Starynkevitch Sep 17 '14 at 18:43
3

The best way is to track what the next time is when you add to the array, then you sleep until that time.

So, when adding a new event to the array, you must decide if it is going to be triggered first, or later than the currently stored 'next event'. Then your loop simply sleeps (maybe periodically waking up every second or so to print an "I'm still running" diagnostic).

This will require a thread that wakes up to trigger the event must be synchronised with a mutex, so it can be prematurely woken up if a new event is added that is going to be fired sooner than the current next event. This thread then re-calculates the next time will be, sets the mutex and waits for either it to be triggered again or a timeout occurs where the timeout will be the right amount of time to wait for the next event's time.

2

The quick and dirty solution is to add a sleep call to yield the processor to other applications. This lowers the CPU usage tremendously.

A better solution if possible is to have your method invoked in a callback. For example, Win32 UI event handling will let you register callbacks for specific events.

  • I used this solution, i added an sleep call, the CPU usage was dramatically lower, thanks! – David T Sep 17 '14 at 21:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.