-
-
Save noktoborus/11ea32ba16f8911940f0bab97bf68d4c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* vim: ft=c ff=unix fenc=utf-8 | |
* file: tv.c | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <stdint.h> | |
#include <stdbool.h> | |
#include <string.h> | |
#include <unistd.h> | |
#include <assert.h> | |
#include <inttypes.h> | |
#include <sys/time.h> | |
/* substract tv2 from tv1, result in tv1 | |
* if tv2 > tv1 result is tv1.tv_sec = 0, tv1.tv_usec = 0 | |
*/ | |
void | |
timeval_substract_tv(struct timeval *tv1, struct timeval *tv2) | |
{ | |
if (tv2->tv_usec > tv1->tv_usec) { | |
if (tv1->tv_sec >= 1) { | |
tv1->tv_sec--; | |
tv1->tv_usec += 1000000; | |
} | |
} | |
if (tv2->tv_sec > tv1->tv_sec || tv2->tv_usec > tv1->tv_usec) { | |
tv1->tv_sec = 0u; | |
tv1->tv_usec = 0u; | |
} else { | |
tv1->tv_sec -= tv2->tv_sec; | |
tv1->tv_usec -= tv2->tv_usec; | |
} | |
} | |
/* substract msec (milliseconds) from tv | |
* if msec > tv result is tv.tv_sec = 0, tv.tv_usec = 0 | |
*/ | |
void | |
timeval_substract_msec(struct timeval *tv, unsigned msec) | |
{ | |
struct timeval tv2 = {}; | |
tv2.tv_sec = msec / 1000u; | |
tv2.tv_usec = (msec % 1000u) * 1000u; | |
timeval_substract_tv(tv, &tv2); | |
} | |
int | |
main(int argc, char *argv[]) | |
{ | |
struct timeval tv1 = {}; | |
tv1.tv_sec = 2; | |
tv1.tv_usec = 0; | |
timeval_substract_msec(&tv1, 1000); | |
printf("tv = %"PRIdPTR".%.06"PRIdPTR"\n", tv1.tv_sec, tv1.tv_usec); | |
assert(tv1.tv_sec == 1 && tv1.tv_usec == 0); | |
tv1.tv_sec = 1; | |
tv1.tv_usec = 5000; | |
timeval_substract_msec(&tv1, 1004); | |
printf("tv = %"PRIdPTR".%.06"PRIdPTR"\n", tv1.tv_sec, tv1.tv_usec); | |
assert(tv1.tv_sec == 0 && tv1.tv_usec == 1000); | |
tv1.tv_sec = 4; | |
tv1.tv_usec = 1000; | |
timeval_substract_msec(&tv1, 4); | |
printf("tv = %"PRIdPTR".%.06"PRIdPTR"\n", tv1.tv_sec, tv1.tv_usec); | |
assert(tv1.tv_sec == 3 && tv1.tv_usec == 997000); | |
tv1.tv_sec = 5; | |
tv1.tv_usec = 2000; | |
timeval_substract_msec(&tv1, 5400); | |
printf("tv = %"PRIdPTR".%.06"PRIdPTR"\n", tv1.tv_sec, tv1.tv_usec); | |
assert(tv1.tv_sec == 0 && tv1.tv_usec == 0); | |
tv1.tv_sec = 0; | |
tv1.tv_usec = 1000; | |
timeval_substract_msec(&tv1, 2); | |
printf("tv = %"PRIdPTR".%.06"PRIdPTR"\n", tv1.tv_sec, tv1.tv_usec); | |
assert(tv1.tv_sec == 0 && tv1.tv_usec == 0); | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment