timing.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #define _POSIX_C_SOURCE 200112L
  2. #define _GNU_SOURCE
  3. #include <stdio.h>
  4. #include <string.h>
  5. #include <unistd.h>
  6. #include <stdint.h>
  7. #include <assert.h>
  8. #include <ctype.h>
  9. #include <time.h>
  10. #include <sched.h>
  11. #include <arpa/inet.h>
  12. #include <sys/time.h>
  13. #include "pci.h"
  14. #include "tools.h"
  15. #include "error.h"
  16. int pcilib_add_timeout(struct timeval *tv, pcilib_timeout_t timeout) {
  17. tv->tv_usec += timeout%1000000;
  18. if (tv->tv_usec > 999999) {
  19. tv->tv_usec -= 1000000;
  20. tv->tv_sec += 1 + timeout/1000000;
  21. } else {
  22. tv->tv_sec += timeout/1000000;
  23. }
  24. return 0;
  25. }
  26. int pcilib_calc_deadline(struct timeval *tv, pcilib_timeout_t timeout) {
  27. gettimeofday(tv, NULL);
  28. pcilib_add_timeout(tv, timeout);
  29. return 0;
  30. }
  31. int pcilib_check_deadline(struct timeval *tve, pcilib_timeout_t timeout) {
  32. int64_t res;
  33. struct timeval tvs;
  34. if (!tve->tv_sec) return 0;
  35. gettimeofday(&tvs, NULL);
  36. res = ((tve->tv_sec - tvs.tv_sec)*1000000 + (tve->tv_usec - tvs.tv_usec));
  37. // Hm... Some problems comparing signed and unsigned. So, sign check first
  38. if ((res < 0)||(res < timeout)) {
  39. return 1;
  40. }
  41. return 0;
  42. }
  43. pcilib_timeout_t pcilib_calc_time_to_deadline(struct timeval *tve) {
  44. int64_t res;
  45. struct timeval tvs;
  46. gettimeofday(&tvs, NULL);
  47. res = ((tve->tv_sec - tvs.tv_sec)*1000000 + (tve->tv_usec - tvs.tv_usec));
  48. if (res < 0) return 0;
  49. return res;
  50. }
  51. int pcilib_sleep_until_deadline(struct timeval *tv) {
  52. struct timespec wait;
  53. pcilib_timeout_t duration;
  54. duration = pcilib_calc_time_to_deadline(tv);
  55. if (duration > 0) {
  56. wait.tv_sec = duration / 1000000;
  57. wait.tv_nsec = 1000 * (duration % 1000000);
  58. nanosleep(&wait, NULL);
  59. }
  60. return 0;
  61. }
  62. pcilib_timeout_t pcilib_timediff(struct timeval *tvs, struct timeval *tve) {
  63. return ((tve->tv_sec - tvs->tv_sec)*1000000 + (tve->tv_usec - tvs->tv_usec));
  64. }
  65. int pcilib_timecmp(struct timeval *tv1, struct timeval *tv2) {
  66. if (tv1->tv_sec > tv2->tv_sec) return 1;
  67. else if (tv1->tv_sec < tv2->tv_sec) return -1;
  68. else if (tv1->tv_usec > tv2->tv_usec) return 1;
  69. else if (tv1->tv_usec < tv2->tv_usec) return -1;
  70. return 0;
  71. }