1 /*
2  * Copyright (C) 2011-2020 Kim Woelders
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a copy
5  * of this software and associated documentation files (the "Software"), to
6  * deal in the Software without restriction, including without limitation the
7  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
8  * sell copies of the Software, and to permit persons to whom the Software is
9  * furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies of the Software, its documentation and marketing & publicity
13  * materials, and acknowledgment shall be given in the documentation, materials
14  * and software packages that this Software was used.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
20  * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22  */
23 #include "config.h"
24 
25 #include <time.h>
26 #if !USE_MONOTONIC_CLOCK
27 #include <sys/time.h>
28 #endif
29 
30 #include "util.h"
31 
32 unsigned int
GetTimeMs(void)33 GetTimeMs(void)
34 {
35 #if USE_MONOTONIC_CLOCK
36    struct timespec     ts;
37 
38    clock_gettime(CLOCK_MONOTONIC, &ts);
39 
40    return (unsigned int)(ts.tv_sec * 1000 + ts.tv_nsec / 1000000);
41 #else
42    struct timeval      timev;
43 
44    gettimeofday(&timev, NULL);
45 
46    return (unsigned int)(timev.tv_sec * 1000 + timev.tv_usec / 1000);
47 #endif
48 }
49 
50 unsigned int
GetTimeUs(void)51 GetTimeUs(void)
52 {
53 #if USE_MONOTONIC_CLOCK
54    struct timespec     ts;
55 
56    clock_gettime(CLOCK_MONOTONIC, &ts);
57 
58    return (unsigned int)(ts.tv_sec * 1000000 + ts.tv_nsec / 1000);
59 #else
60    struct timeval      timev;
61 
62    gettimeofday(&timev, NULL);
63 
64    return (unsigned int)(timev.tv_sec * 1000000 + timev.tv_usec);
65 #endif
66 }
67 
68 void
SleepUs(unsigned int tus)69 SleepUs(unsigned int tus)
70 {
71    struct timespec     ts;
72 
73    ts.tv_sec = tus / 1000000;
74    tus -= ts.tv_sec * 1000000;
75    ts.tv_nsec = tus * 1000;
76 
77    while (nanosleep(&ts, &ts))
78       ;
79 }
80