Initial revision
[platform/upstream/glib.git] / 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
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19 #include <sys/time.h>
20 #include <unistd.h>
21 #include "glib.h"
22
23
24 typedef struct _GRealTimer GRealTimer;
25
26 struct _GRealTimer
27 {
28   struct timeval start;
29   struct timeval end;
30   gint active;
31 };
32
33
34 GTimer*
35 g_timer_new (void)
36 {
37   GRealTimer *timer;
38
39   timer = g_new (GRealTimer, 1);
40   timer->active = TRUE;
41
42   gettimeofday (&timer->start, NULL);
43
44   return ((GTimer*) timer);
45 }
46
47 void
48 g_timer_destroy (GTimer *timer)
49 {
50   g_assert (timer != NULL);
51
52   g_free (timer);
53 }
54
55 void
56 g_timer_start (GTimer *timer)
57 {
58   GRealTimer *rtimer;
59
60   g_assert (timer != NULL);
61
62   rtimer = (GRealTimer*) timer;
63   gettimeofday (&rtimer->start, NULL);
64   rtimer->active = 1;
65 }
66
67 void
68 g_timer_stop (GTimer *timer)
69 {
70   GRealTimer *rtimer;
71
72   g_assert (timer != NULL);
73
74   rtimer = (GRealTimer*) timer;
75   gettimeofday (&rtimer->end, NULL);
76   rtimer->active = 0;
77 }
78
79 void
80 g_timer_reset (GTimer *timer)
81 {
82   GRealTimer *rtimer;
83
84   g_assert (timer != NULL);
85
86   rtimer = (GRealTimer*) timer;
87   gettimeofday (&rtimer->start, NULL);
88 }
89
90 gdouble
91 g_timer_elapsed (GTimer *timer,
92                  gulong *microseconds)
93 {
94   GRealTimer *rtimer;
95   struct timeval elapsed;
96   gdouble total;
97
98   g_assert (timer != NULL);
99
100   rtimer = (GRealTimer*) timer;
101
102   if (rtimer->active)
103     gettimeofday (&rtimer->end, NULL);
104
105   if (rtimer->start.tv_usec > rtimer->end.tv_usec)
106     {
107       rtimer->end.tv_usec += 1000000;
108       rtimer->end.tv_sec--;
109     }
110
111   elapsed.tv_usec = rtimer->end.tv_usec - rtimer->start.tv_usec;
112   elapsed.tv_sec = rtimer->end.tv_sec - rtimer->start.tv_sec;
113
114   total = elapsed.tv_sec + ((gdouble) elapsed.tv_usec / 1e6);
115
116   if (microseconds)
117     *microseconds = elapsed.tv_usec;
118
119   return total;
120 }