FloKl
FloKl

Reputation: 35

programming EXACT timer which calles a function in c language every x seconds

I need some help with a part of my Programm. I want to call a function EXACTLY every x seconds. The problem with the most soultions is, that the time to call the sleep() or w/e function stacks over time.

An example: If I want to call a function every second with sleep(1), it takes 1 second + a very small x (time to call the sleep() function). So it takes 1,x seconds. Not 1,0 second.

Over a long period of time the x stacks to a "huge amount" of time.

I want a code snippet which executes something EXACTLY every second so that I get exact timestamps without any additional delay. I think it's part of the real-time-programming problem.

Is there some working code out there for that?

Please help me out with that. :)

FloKL

Upvotes: 0

Views: 180

Answers (3)

user3629249
user3629249

Reputation: 16540

suggest using the function: setitimer() which is exposed via the header file: <sys/timer.h>.

Suggest reading the MAN page for setitimer for all the details

Upvotes: 1

angelito
angelito

Reputation: 461

 int X = 10;
 int t1 = (int)time(NULL);
 while(1==1){
     // execute your process
     ...
     // calculate next tick
     t1 = t1 + X;
     sleep(t1 - (int)time(NULL));
 }

Upvotes: 2

Bathsheba
Bathsheba

Reputation: 234865

You can recode your call to sleep to pass effectively 1 - a rather than 1 where a is an adjustment calculate to eliminate the accumulated x. (Clearly you'll need to adjust the sleep unit as a will be less than 1 in general).

Otherwise C provides no facility directly for an "exact" timing. You'll need to use external hardware for that. And expect to pay a lot of money for atomic-clock level accuracy.

Upvotes: 1

Related Questions