time.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. struct timespec begin;
  43. void timeInitialize(int rel)
  44. {
  45. if(clock_gettime(CLOCK_REALTIME, &begin) < 0)
  46. {
  47. perror("clock_gettime()");
  48. exit(1);
  49. }
  50. begin.tv_sec += rel;
  51. }
  52. struct timespec timeGetRelative()
  53. {
  54. struct timespec r;
  55. if(clock_gettime(CLOCK_REALTIME, &r) < 0)
  56. {
  57. perror("clock_gettime()");
  58. exit(1);
  59. }
  60. return timeDiff(r, begin);
  61. }
  62. int timeSleepUntil(struct timespec t)
  63. {
  64. struct timespec current = timeGetRelative();
  65. return timeSleep(timeDiff(t, current));
  66. }
  67. struct timespec timeCreate(time_t s, long ns)
  68. {
  69. struct timespec r;
  70. r.tv_sec = s;
  71. r.tv_nsec = ns;
  72. return r;
  73. }
  74. int timeInFuture(struct timespec t)
  75. {
  76. struct timespec tmp = timeGetRelative();
  77. tmp = timeDiff(t, tmp);
  78. return tmp.tv_sec >= 0;
  79. }