Special value -1.0 means 'could not get timings' on current platform.
[yaz-moved-to-github.git] / src / timing.c
1 /*
2  * Copyright (C) 1995-2007, Index Data ApS
3  * See the file LICENSE for details.
4  *
5  * $Id: timing.c,v 1.2 2007-01-05 11:44:49 adam Exp $
6  */
7
8 /**
9  * \file timing.c
10  * \brief Timing Utilities
11  */
12
13 #if HAVE_CONFIG_H
14 #include <config.h>
15 #endif
16
17 #include <stdlib.h>
18
19 #if HAVE_SYS_TIMES_H
20 #include <sys/times.h>
21 #endif
22 #if HAVE_SYS_TIME_H
23 #include <sys/time.h>
24 #endif
25 #include <time.h>
26
27 #include <yaz/xmalloc.h>
28 #include <yaz/timing.h>
29
30 struct yaz_timing {
31 #if HAVE_SYS_TIMES_H
32     struct tms tms1, tms2;
33 #endif
34 #if HAVE_SYS_TIME_H
35     struct timeval start_time, end_time;
36 #endif
37     double real_sec, user_sec, sys_sec;
38 };
39
40 yaz_timing_t yaz_timing_create(void)
41 {
42     yaz_timing_t t = xmalloc(sizeof(*t));
43     yaz_timing_start(t);
44     return t;
45 }
46
47 void yaz_timing_start(yaz_timing_t t)
48 {
49 #if HAVE_SYS_TIMES_H
50     times(&t->tms1);
51     t->user_sec = 0.0;
52     t->sys_sec = 0.0;
53 #else
54     t->user_sec = -1.0;
55     t->sys_sec = -1.0;
56 #endif
57 #if HAVE_SYS_TIME_H
58     gettimeofday(&t->start_time, 0);
59     t->real_sec = 0.0;
60 #else
61     t->real_sec = -1.0;
62 #endif
63 }
64
65 void yaz_timing_stop(yaz_timing_t t)
66 {
67 #if HAVE_SYS_TIMES_H
68     times(&t->tms2);
69     
70     t->user_sec = (double) (t->tms2.tms_utime - t->tms1.tms_utime)/100;
71     t->sys_sec = (double) (t->tms2.tms_stime - t->tms1.tms_stime)/100;
72 #endif
73 #if HAVE_SYS_TIME_H
74     gettimeofday(&t->end_time, 0);
75     t->real_sec = ((t->end_time.tv_sec - t->start_time.tv_sec) * 1000000.0 +
76                    t->end_time.tv_usec - t->start_time.tv_usec) / 1000000;
77     
78 #endif
79 }
80
81 double yaz_timing_get_real(yaz_timing_t t)
82 {
83     return t->real_sec;
84 }
85
86 double yaz_timing_get_user(yaz_timing_t t)
87 {
88     return t->user_sec;
89 }
90
91 double yaz_timing_get_sys(yaz_timing_t t)
92 {
93     return t->sys_sec;
94 }
95
96 void yaz_timing_destroy(yaz_timing_t *tp)
97 {
98     if (*tp)
99     {
100         xfree(*tp);
101         *tp = 0;
102     }
103 }
104
105 /*
106  * Local variables:
107  * c-basic-offset: 4
108  * indent-tabs-mode: nil
109  * End:
110  * vim: shiftwidth=4 tabstop=8 expandtab
111  */
112