libtrbase  1.0.2
Web server and task management solution.
timer_get.c
Go to the documentation of this file.
1 /**
2  * \file
3  *
4  * \author Georg Hopp
5  *
6  * \copyright
7  * Copyright © 2014 Georg Hopp
8  *
9  * This program is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation, either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program. If not, see <http://www.gnu.org/licenses/>.
21  */
22 
23 #define _POSIX_C_SOURCE 199309L
24 
25 #include <time.h>
26 #include <limits.h>
27 
28 #include "trbase.h"
29 
30 unsigned long
31 TR_timerGet(TR_Timer this, unsigned long * missed)
32 {
33  struct timespec now;
34  unsigned long long elapsed;
35  unsigned long sec_factor;
36  long nan_factor;
37  unsigned long _missed;
38 
39  clock_gettime(CLOCK_REALTIME, &now);
40 
41  switch (this->base) {
42  case TR_TBASE_NAN:
43  sec_factor = 1000 * 1000 * 1000;
44  break;
45  case TR_TBASE_MIC:
46  sec_factor = 1000 * 1000;
47  break;
48  default:
49  case TR_TBASE_MIL:
50  sec_factor = 1000;
51  break;
52  case TR_TBASE_SEC:
53  sec_factor = 1;
54  break;
55  }
56 
57  nan_factor = 1000 * 1000 * 1000 / sec_factor;
58  elapsed = (now.tv_sec - this->sec) * sec_factor
59  + (now.tv_nsec - this->nsec) / nan_factor;
60 
61  _missed = elapsed / this->timeout;
62  if (_missed) {
63  this->sec += _missed * this->timeout * sec_factor / nan_factor;
64  this->nsec += _missed * this->timeout * sec_factor % nan_factor;
65  if (missed) *missed = _missed;
66  } else {
67  if (missed) *missed = 0;
68  }
69 
70  return this->timeout - (elapsed % this->timeout);
71 }
72 
73 // vim: set ts=4 sw=4:
unsigned long TR_timerGet(TR_Timer this, unsigned long *missed)
Definition: timer_get.c:31