I've written a code to ensure each loop of while(1) loop to take specific amount of time (in this example 10000µS which equals to 0.01 seconds). The problem is this code works pretty well at the start but somehow stops after less than a minute. It's like there is a limit of accessing linux time. For now, I am initializing a boolean variable to make this time calculation run once instead infinite. Since performance varies over time, it'd be good to calculate the computation time for each loop. Is there any other way to accomplish this?
void some_function(){
struct timeval tstart,tend;
while (1){
gettimeofday (&tstart, NULL);
...
Some computation
...
gettimeofday (&tend, NULL);
diff = (tend.tv_sec - tstart.tv_sec)*1000000L+(tend.tv_usec - tstart.tv_usec);
usleep(10000-diff);
}
}
Well, the computation you make to get the difference is wrong:
You are mixing different integer types, missing that
tv_usec
can be anunsigned
quantity, which your are substracting from anotherunsigned
and can overflow.... after that, you get as result a full second plus a quantity that is around4.0E09usec
. This is some 4000sec. or more than an hour.... aproximately. It is better to check if there's some carry, and in that case, to incrementtv_sec
, and then substract10000000
fromtv_usec
to get a proper positive value.I don't know the implementation you are using for
struct timeval
but the most probable is thattv_sec
is atime_t
(this can be even 64bit) whiletv_usec
normally is just aunsigned
32 bit value, as it it not going to go further from1000000
.Let me illustrate... suppose you have elapsed 100ms doing calculations.... and this happens to occur in the middle of a second.... you have
when you substract, it leads to:
but let's suppose you have done your computation while the second changes
the time difference is again 100msec, but now, when you calculate your expression you get, for the first part, 1000000 (one full second) but, after substracting the second part you get
23456 - 923456 =*=> 4294067296
(*) with the overflow. so you get tousleep(4295067296)
or4295s.
or1h 11m
more. I think you have not had enough patience to wait for it to finish... but this is something that can be happening to your program, depending on howstruct timeval
is defined.A proper way to make carry to work is to reorder the summation to do all the additions first and then the substractions. This forces casts to signed integers when dealing with
signed
andunsigned
together, and prevents a negative overflow inunsigned
s.which is parsed as