fork download
  1. #include <stdio.h>
  2.  
  3. struct timeval
  4. {
  5. long tv_sec;
  6. long tv_usec;
  7. };
  8.  
  9. int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y)
  10. {
  11. // preserve *y
  12. struct timeval yy = *y;
  13. y = &yy;
  14.  
  15. /* Perform the carry for the later subtraction by updating y. */
  16. if (x->tv_usec < y->tv_usec) {
  17. int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
  18. y->tv_usec -= 1000000 * nsec;
  19. y->tv_sec += nsec;
  20. }
  21. if (x->tv_usec - y->tv_usec > 1000000) {
  22. int nsec = (y->tv_usec - x->tv_usec) / 1000000;
  23. y->tv_usec += 1000000 * nsec;
  24. y->tv_sec -= nsec;
  25. }
  26.  
  27. /* Compute the time remaining to wait.
  28.   tv_usec is certainly positive. */
  29. result->tv_sec = x->tv_sec - y->tv_sec;
  30. result->tv_usec = x->tv_usec - y->tv_usec;
  31.  
  32. /* Return 1 if result is negative. */
  33. return x->tv_sec < y->tv_sec;
  34. }
  35.  
  36. struct timeval testData00 = { 0, 0 };
  37. struct timeval testData01 = { 0, 1 };
  38. struct timeval testData01000000 = { 0, 1000000 };
  39. struct timeval testData01000001 = { 0, 1000001 };
  40.  
  41. int main(void)
  42. {
  43. struct timeval diff;
  44. int res;
  45.  
  46. res = timeval_subtract(&diff, &testData00, &testData00);
  47. printf("%d %ld:%ld\n", res, diff.tv_sec, diff.tv_usec);
  48.  
  49. res = timeval_subtract(&diff, &testData01, &testData01);
  50. printf("%d %ld:%ld\n", res, diff.tv_sec, diff.tv_usec);
  51.  
  52. res = timeval_subtract(&diff, &testData01, &testData00);
  53. printf("%d %ld:%ld\n", res, diff.tv_sec, diff.tv_usec);
  54.  
  55. res = timeval_subtract(&diff, &testData00, &testData01);
  56. printf("%d %ld:%ld\n", res, diff.tv_sec, diff.tv_usec);
  57.  
  58. res = timeval_subtract(&diff, &testData01000000, &testData00);
  59. printf("%d %ld:%ld\n", res, diff.tv_sec, diff.tv_usec);
  60.  
  61. res = timeval_subtract(&diff, &testData01000001, &testData00);
  62. printf("%d %ld:%ld\n", res, diff.tv_sec, diff.tv_usec);
  63.  
  64. return 0;
  65. }
  66.  
Success #stdin #stdout 0s 1832KB
stdin
Standard input is empty
stdout
0 0:0
0 0:0
0 0:1
1 -1:999999
0 0:1000000
1 -1:2000001