Fedora Linux Support Community & Resources Center
Old 24th August 2010, 03:00 PM
CowTux Offline
Registered User
Join Date: Feb 2010
Posts: 32
how to use less CPU on loops


This is probably a weird question, so prepare yourselves.

I'm writing a little program to display an estimate of my battery life on my xmobar status bar. I was using a program I've found which watches for CAPSLOCK and does something similar. However, in my program the infinite while loop uses way too much of my CPU. I've picked apart the example CAPSLOCK program and I've found that the reason it doesn't take 99% of my CPU is this

XNextEvent(disp, &ev.core);
I'm guessing this function waits for an X event before moving on to the next line of code. So, the effect of this is that the while(1) loop in which this function call lives slows down and doesn't consume too much CPU.

So, does anyone know a way to get a similar effect without having to bother the X server?

while(1) {
  look at battery file and calculate time left

  print info to stdout

  wait a few seconds


Reply With Quote
Old 24th August 2010, 04:02 PM
droidhacker Offline
Registered User
Join Date: Oct 2009
Posts: 824
Re: how to use less CPU on loops

You should try exactly what you suggest... throw a sleep or usleep into your loop. See "man 3 sleep" and "man 3 usleep".

while (1){
sleep(10); //sleeps for 10 seconds

However, if you can find something to wait on rather than polling, it will save you from waking the system up every time the loop iterates.
Reply With Quote
Old 24th August 2010, 08:10 PM
CowTux Offline
Registered User
Join Date: Feb 2010
Posts: 32
Re: how to use less CPU on loops

Thanks for the advice.

sleep( ) has done the trick for me.

Reply With Quote

cpu, loops

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Fedora 9 Setup Agent loops dean guenther Installation, Upgrades and Live Media 4 23rd June 2008 04:06 PM
C++ question about loops girgori Programming & Packaging 8 28th September 2006 05:49 AM
New FC5 install - boot loops on udev zdenisl EOL (End Of Life) Versions 2 16th June 2006 08:27 PM
Python newbie - loops sycamorex Programming & Packaging 6 27th January 2006 08:01 PM

Current GMT-time: 08:09 (Wednesday, 23-08-2017)

TopSubscribe to XML RSS for all Threads in all ForumsFedoraForumDotOrg Archive

All trademarks, and forum posts in this site are property of their respective owner(s).
FedoraForum.org is privately owned and is not directly sponsored by the Fedora Project or Red Hat, Inc.

Privacy Policy | Term of Use | Posting Guidelines | Archive | Contact Us | Founding Members

Powered by vBulletin® Copyright ©2000 - 2012, vBulletin Solutions, Inc.

FedoraForum is Powered by RedHat