56 static struct timer *first_timer = NULL;
58 static double timer_freq;
59 static int timer_countdown_to_next_gettimeofday;
60 static double timer_current_time;
61 static double timer_current_time_step;
63 static int timer_is_running;
65 #define SECONDS_BETWEEN_GETTIMEOFDAY_SYNCH 1.65
78 struct timer *newtimer;
82 if (
freq <= 0.00000001)
92 newtimer->
next = first_timer;
93 first_timer = newtimer;
106 struct timer *prev = NULL, *cur = first_timer;
108 while (cur != NULL && cur !=
t) {
115 first_timer = cur->
next;
120 fprintf(stderr,
"attempt to remove timer %p which "
121 "doesn't exist. aborting\n",
t);
134 if (
t->freq == new_freq)
139 if (new_freq <= 0.00000001)
140 new_freq = 0.00000001;
142 t->interval = 1.0 / new_freq;
143 t->next_tick_at = timer_current_time +
t->interval;
157 timer_current_time += timer_current_time_step;
159 if ((--timer_countdown_to_next_gettimeofday) < 0) {
160 gettimeofday(&tv, NULL);
163 if (tv.tv_usec < 0) {
164 tv.tv_usec += 1000000;
171 double diff = tv.tv_usec * 0.000001 + tv.tv_sec
172 - timer_current_time;
173 printf(
"timer: lagging behind %f seconds\n", diff);
179 timer_current_time = ( (tv.tv_usec * 0.000001 + tv.tv_sec) +
180 timer_current_time ) / 2;
182 timer_countdown_to_next_gettimeofday = (int64_t) (timer_freq *
186 while (
timer != NULL) {
196 printf(
"T"); fflush(stdout);
209 struct itimerval val;
210 struct sigaction saction;
212 if (timer_is_running)
215 timer_is_running = 1;
218 timer_current_time = 0.0;
221 while (
timer != NULL) {
225 val.it_interval.tv_sec = 0;
226 val.it_interval.tv_usec = (int) (1000000.0 / timer_freq);
227 val.it_value.tv_sec = 0;
228 val.it_value.tv_usec = (int) (1000000.0 / timer_freq);
230 memset(&saction, 0,
sizeof(saction));
231 saction.sa_handler = timer_tick;
232 saction.sa_flags = SA_RESTART;
234 sigaction(SIGALRM, &saction, NULL);
236 setitimer(ITIMER_REAL, &val, NULL);
247 struct itimerval val;
248 struct sigaction saction;
250 if (!timer_is_running)
253 timer_is_running = 0;
255 val.it_interval.tv_sec = 0;
256 val.it_interval.tv_usec = 0;
257 val.it_value.tv_sec = 0;
258 val.it_value.tv_usec = 0;
260 setitimer(ITIMER_REAL, &val, NULL);
262 memset(&saction, 0,
sizeof(saction));
263 saction.sa_handler = NULL;
265 sigaction(SIGALRM, &saction, NULL);
270 static void timer_tick_test(
struct timer *
t,
void *extra)
272 printf((
char *) extra); fflush(stdout);
285 timer_current_time = 0.0;
286 timer_is_running = 0;
287 timer_countdown_to_next_gettimeofday = 0;
290 timer_current_time_step = 1.0 / timer_freq;