1 /////////////////////////////////////////////////////////////////////////////// 2 // 3 /// \file mytime.c 4 /// \brief Time handling functions 5 // 6 // Author: Lasse Collin 7 // 8 // This file has been put into the public domain. 9 // You can do whatever you want with this file. 10 // 11 /////////////////////////////////////////////////////////////////////////////// 12 13 #include "private.h" 14 15 #if defined(HAVE_CLOCK_GETTIME) && defined(HAVE_CLOCK_MONOTONIC) 16 # include <time.h> 17 #else 18 # include <sys/time.h> 19 #endif 20 21 uint64_t opt_flush_timeout = 0; 22 23 static uint64_t start_time; 24 static uint64_t next_flush; 25 26 27 /// \brief Get the current time as milliseconds 28 /// 29 /// It's relative to some point but not necessarily to the UNIX Epoch. 30 static uint64_t 31 mytime_now(void) 32 { 33 #if defined(HAVE_CLOCK_GETTIME) && defined(HAVE_CLOCK_MONOTONIC) 34 // If CLOCK_MONOTONIC was available at compile time but for some 35 // reason isn't at runtime, fallback to CLOCK_REALTIME which 36 // according to POSIX is mandatory for all implementations. 37 static clockid_t clk_id = CLOCK_MONOTONIC; 38 struct timespec tv; 39 while (clock_gettime(clk_id, &tv)) 40 clk_id = CLOCK_REALTIME; 41 42 return (uint64_t)tv.tv_sec * 1000 + (uint64_t)(tv.tv_nsec / 1000000); 43 #else 44 struct timeval tv; 45 gettimeofday(&tv, NULL); 46 return (uint64_t)tv.tv_sec * 1000 + (uint64_t)(tv.tv_usec / 1000); 47 #endif 48 } 49 50 51 extern void 52 mytime_set_start_time(void) 53 { 54 start_time = mytime_now(); 55 return; 56 } 57 58 59 extern uint64_t 60 mytime_get_elapsed(void) 61 { 62 return mytime_now() - start_time; 63 } 64 65 66 extern void 67 mytime_set_flush_time(void) 68 { 69 next_flush = mytime_now() + opt_flush_timeout; 70 return; 71 } 72 73 74 extern int 75 mytime_get_flush_timeout(void) 76 { 77 if (opt_flush_timeout == 0 || opt_mode != MODE_COMPRESS) 78 return -1; 79 80 const uint64_t now = mytime_now(); 81 if (now >= next_flush) 82 return 0; 83 84 const uint64_t remaining = next_flush - now; 85 return remaining > INT_MAX ? INT_MAX : (int)remaining; 86 } 87