Infinate loops/Battery consumption

This is a discussion on Infinate loops/Battery consumption within the Linux Programming forums, part of the Platform Specific Boards category; Hi there. I'm trying to understand how i can make the code below more efficient. I'm trying find a way ...

  1. #1
    Registered User
    Join Date
    Jul 2008
    Posts
    5

    Infinate loops/Battery consumption

    Hi there. I'm trying to understand how i can make the code below more efficient. I'm trying find a way to execute the get_uptime() function every second. The code works but because of the infinite loop the CPU resources are at 100%. I'm trying to practice making an application for my phone (N900). I'm aware that the code below will drain the battery very quickly.

    Any hints please?

    Cheers

    Code:
    #include<stdio.h>
    #include<sys/time.h>
    #include<signal.h> 
    
    void get_uptime(int signo)
    {
    	FILE *fd;
    	float buf;
    	fd = fopen("/proc/uptime","r");
    	fscanf(fd,"%f",&buf);
    	printf("%f\n",buf);
    	fclose(fd);
    }
    
    int main(void)
    {
    
    	struct timeval delay;
    	int ret;
    
    	delay.tv_sec = 1;
    	delay.tv_usec = 0;
    		
    	for(;;){
    
    		select(1,NULL,NULL,NULL,&delay);
    		get_uptime(0);
    	}
    
    return 0;
    }

  2. #2
    Registered User
    Join Date
    Oct 2008
    Location
    TX
    Posts
    2,047
    Try sleep()'ing for one second instead of timing out using select().

  3. #3
    Captain Crash brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,243
    The use of select as a portable timeout is pretty reliable, but maybe not in this case. I agree, if you don't need sub-second delays then sleep() is a better choice.
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Measuring system power consumption on Windows?
    By cyberfish in forum Tech Board
    Replies: 0
    Last Post: 07-17-2009, 12:03 AM
  2. calculate memory consumption and cpu usage
    By GermanDev in forum C++ Programming
    Replies: 18
    Last Post: 12-14-2008, 04:32 PM
  3. consumption
    By khalid in forum C Programming
    Replies: 6
    Last Post: 12-16-2007, 07:47 PM
  4. Move Infinate value to a vector
    By swanley007 in forum C++ Programming
    Replies: 6
    Last Post: 10-26-2005, 06:19 AM
  5. Infinate Loop
    By sreetvert83 in forum C++ Programming
    Replies: 10
    Last Post: 07-28-2005, 08:17 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21