]> Pileus Git - ~andy/gtk/blob - glib/gtimer.c
c3b720df9639b2d9a704c828b69a015ed5ad2f99
[~andy/gtk] / glib / gtimer.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the Free
16  * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17  */
18 #include <sys/time.h>
19 #include <unistd.h>
20 #include "glib.h"
21
22
23 typedef struct _GRealTimer GRealTimer;
24
25 struct _GRealTimer
26 {
27   struct timeval start;
28   struct timeval end;
29   gint active;
30 };
31
32
33 GTimer*
34 g_timer_new ()
35 {
36   GRealTimer *timer;
37
38   timer = g_new (GRealTimer, 1);
39   timer->active = TRUE;
40
41   gettimeofday (&timer->start, NULL);
42
43   return ((GTimer*) timer);
44 }
45
46 void
47 g_timer_destroy (GTimer *timer)
48 {
49   g_assert (timer != NULL);
50
51   g_free (timer);
52 }
53
54 void
55 g_timer_start (GTimer *timer)
56 {
57   GRealTimer *rtimer;
58
59   g_assert (timer != NULL);
60
61   rtimer = (GRealTimer*) timer;
62   gettimeofday (&rtimer->start, NULL);
63   rtimer->active = 1;
64 }
65
66 void
67 g_timer_stop (GTimer *timer)
68 {
69   GRealTimer *rtimer;
70
71   g_assert (timer != NULL);
72
73   rtimer = (GRealTimer*) timer;
74   gettimeofday (&rtimer->end, NULL);
75   rtimer->active = 0;
76 }
77
78 void
79 g_timer_reset (GTimer *timer)
80 {
81   GRealTimer *rtimer;
82
83   g_assert (timer != NULL);
84
85   rtimer = (GRealTimer*) timer;
86   gettimeofday (&rtimer->start, NULL);
87 }
88
89 gdouble
90 g_timer_elapsed (GTimer *timer,
91                  gulong *microseconds)
92 {
93   GRealTimer *rtimer;
94   struct timeval elapsed;
95   gdouble total;
96
97   g_assert (timer != NULL);
98
99   rtimer = (GRealTimer*) timer;
100
101   if (rtimer->active)
102     gettimeofday (&rtimer->end, NULL);
103
104   if (rtimer->start.tv_usec > rtimer->end.tv_usec)
105     {
106       rtimer->end.tv_usec += 1000000;
107       rtimer->end.tv_sec--;
108     }
109
110   elapsed.tv_usec = rtimer->end.tv_usec - rtimer->start.tv_usec;
111   elapsed.tv_sec = rtimer->end.tv_sec - rtimer->start.tv_sec;
112
113   total = elapsed.tv_sec + ((gdouble) elapsed.tv_usec / 1e6);
114
115   if (microseconds)
116     *microseconds = elapsed.tv_usec;
117
118   return total;
119 }