fork(4) 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.  
  39. int main(void)
  40. {
  41. struct timeval diff;
  42. int res;
  43.  
  44. res = timeval_subtract(&diff, &testData00, &testData00);
  45. printf("%d %ld:%ld\n", res, diff.tv_sec, diff.tv_usec);
  46.  
  47. res = timeval_subtract(&diff, &testData01, &testData01);
  48. printf("%d %ld:%ld\n", res, diff.tv_sec, diff.tv_usec);
  49.  
  50. res = timeval_subtract(&diff, &testData01, &testData00);
  51. printf("%d %ld:%ld\n", res, diff.tv_sec, diff.tv_usec);
  52.  
  53. res = timeval_subtract(&diff, &testData00, &testData01);
  54. printf("%d %ld:%ld\n", res, diff.tv_sec, diff.tv_usec);
  55.  
  56. return 0;
  57. }
  58.  
Success #stdin #stdout 0s 1788KB
stdin
Standard input is empty
stdout
0 0:0
0 0:0
0 0:1
1 -1:999999