time.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. /*
  2. Copyright (C) 2014 Olivier Marty <olivier.marty.m at gmail.com>
  3. This program is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU General Public License
  5. as published by the Free Software Foundation; either version 2
  6. of the License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program; if not, write to the Free Software
  13. Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  14. */
  15. #include "time.h"
  16. #include <errno.h>
  17. #include <stdlib.h>
  18. int timeSleep(struct timespec t)
  19. {
  20. int r = -2;
  21. if(t.tv_sec >= 0)
  22. {
  23. do
  24. {
  25. r = nanosleep(&t, &t);
  26. } while(errno == EINTR);
  27. }
  28. return r;
  29. }
  30. struct timespec timeDiff(struct timespec a, struct timespec b)
  31. {
  32. struct timespec r;
  33. r.tv_sec = a.tv_sec - b.tv_sec;
  34. r.tv_nsec = a.tv_nsec - b.tv_nsec;
  35. if(r.tv_nsec < 0)
  36. {
  37. r.tv_nsec += 1000000000;
  38. r.tv_sec -= 1;
  39. }
  40. return r;
  41. }
  42. // f should be >= 0
  43. struct timespec timeFactor(struct timespec a, double f)
  44. {
  45. struct timespec r;
  46. r.tv_sec = f*a.tv_sec;
  47. r.tv_nsec = f*a.tv_nsec;
  48. while(r.tv_nsec > 1000000000)
  49. {
  50. r.tv_nsec -= 1000000000;
  51. r.tv_sec += 1;
  52. }
  53. return r;
  54. }
  55. struct timespec begin;
  56. void timeInitialize(int rel)
  57. {
  58. if(clock_gettime(CLOCK_REALTIME, &begin) < 0)
  59. {
  60. perror("clock_gettime()");
  61. exit(1);
  62. }
  63. begin.tv_sec += rel;
  64. }
  65. struct timespec timeGetRelative()
  66. {
  67. struct timespec r;
  68. if(clock_gettime(CLOCK_REALTIME, &r) < 0)
  69. {
  70. perror("clock_gettime()");
  71. exit(1);
  72. }
  73. return timeDiff(r, begin);
  74. }
  75. int timeSleepUntil(struct timespec t)
  76. {
  77. struct timespec current = timeGetRelative();
  78. return timeSleep(timeDiff(t, current));
  79. }
  80. struct timespec timeCreate(time_t s, long ns)
  81. {
  82. struct timespec r;
  83. r.tv_sec = s;
  84. r.tv_nsec = ns;
  85. return r;
  86. }
  87. int timeInFuture(struct timespec t)
  88. {
  89. struct timespec tmp = timeGetRelative();
  90. tmp = timeDiff(t, tmp);
  91. return tmp.tv_sec >= 0;
  92. }