PDA

View Full Version : Infinate loops/Battery consumption



phil128
07-27-2010, 05:50 PM
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



#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;
}

itCbitC
07-27-2010, 07:43 PM
Try sleep()'ing for one second instead of timing out using select().

brewbuck
07-27-2010, 08:06 PM
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.