Re: Repeated timeouts period

> To answer Greg Breland's question: here is the typical piece of code one
> would use to display a second-accurate clock:
> GtkLabel *clock_label;
> GTimer *clock_timer;
> ...
>     clock_label = gtk_label_new("0");
>     /* add it somewhere in the GUI */
>     clock_timer = g_timer_new();
>     g_timeout_add(1000, update_clock, NULL);
>     g_timer_start(clock_timer);
> ...
> static gboolean
> update_clock(gpointer dummy)
> {
>     char buf[10];
>     sprintf(buf, "%d", (int)g_timer_elapsed(clock_timer, NULL));
>     gtk_label_set_text(GTK_LABEL(clock_label), buf);
>     return(TRUE);
> }
> But look at the actual times where gtk_label_set_text will be called on a
> moderately-loaded system: 1.005, 2.01, 3.015... 60.300... 120.600. After

in this example, the problem is really related to rounding.
g_timer_elapsed() will return the correct value, but you round it (in an
unpredictable way from a portability perspective by casting to int) to
some integer number of seconds. if you always rounded to the nearest
integer, you would not see the irregularities you describe; rather the
clock's imprecision would be limited to 0.5 seconds, which is the
smallest it can be possibly be.

the clock does not get progressively less accurate over time. its
accuracy is always the same: +/- 0.5 seconds, and that is not because of
the way the timeout is called, but because you wanted a second-
resolution clock.


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]