#include <stdio.h>
struct timeval
{
long tv_sec;
long tv_usec;
};
int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y)
{
// preserve *y
struct timeval yy = *y;
y = &yy;
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec) {
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000) {
int nsec = (y->tv_usec - x->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
tv_usec is certainly positive. */
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
struct timeval testData00 = { 0, 0 };
struct timeval testData01 = { 0, 1 };
struct timeval testData01000000 = { 0, 1000000 };
struct timeval testData01000001 = { 0, 1000001 };
int main(void)
{
struct timeval diff;
int res;
res = timeval_subtract(&diff, &testData00, &testData00);
printf("%d %ld:%ld\n", res
, diff.
tv_sec, diff.
tv_usec);
res = timeval_subtract(&diff, &testData01, &testData01);
printf("%d %ld:%ld\n", res
, diff.
tv_sec, diff.
tv_usec);
res = timeval_subtract(&diff, &testData01, &testData00);
printf("%d %ld:%ld\n", res
, diff.
tv_sec, diff.
tv_usec);
res = timeval_subtract(&diff, &testData00, &testData01);
printf("%d %ld:%ld\n", res
, diff.
tv_sec, diff.
tv_usec);
res = timeval_subtract(&diff, &testData01000000, &testData00);
printf("%d %ld:%ld\n", res
, diff.
tv_sec, diff.
tv_usec);
res = timeval_subtract(&diff, &testData01000001, &testData00);
printf("%d %ld:%ld\n", res
, diff.
tv_sec, diff.
tv_usec);
return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CgpzdHJ1Y3QgdGltZXZhbAp7CiAgbG9uZyB0dl9zZWM7CiAgbG9uZyB0dl91c2VjOwp9OwoKaW50IHRpbWV2YWxfc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