Last active
March 15, 2020 12:52
-
-
Save bacher09/a1005db40fb5c4a5310a86d20122c66a to your computer and use it in GitHub Desktop.
This file contains 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
$ ./test | |
1.0 | |
0.1000 | |
0.112 | |
0.112 | |
2652 49490604 |
This file contains 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
#include <stdio.h> | |
#include <time.h> | |
#define NSEC_PER_SEC 1000000000L | |
#define NSEC_PRECISION (NSEC_PER_SEC / 1000) | |
static void time_since_start(char *str, size_t size, struct timespec cur_time) | |
{ | |
int ret; | |
long nsec, sec; | |
nsec = cur_time.tv_nsec; | |
sec = cur_time.tv_sec; | |
if (nsec < 0) { | |
nsec += NSEC_PER_SEC; | |
sec--; | |
} | |
nsec = (nsec + (NSEC_PRECISION / 2)) / NSEC_PRECISION; | |
ret = snprintf(str, size, "%ld.%ld", sec, nsec); | |
if (ret < 0) { | |
str[size - 1] = '\0'; | |
} | |
} | |
int main(int argc, char *argv[]) { | |
static struct timespec cur_time; | |
char time_since[16]; | |
cur_time.tv_sec = 1; | |
cur_time.tv_nsec = 9; | |
time_since_start(time_since, sizeof(time_since), cur_time); | |
printf("%s\n", time_since); // prints 1.0 | |
cur_time.tv_sec = 0; | |
cur_time.tv_nsec = 1000000009; | |
time_since_start(time_since, sizeof(time_since), cur_time); | |
printf("%s\n", time_since); // prints 0.1000 | |
cur_time.tv_sec = 0; | |
cur_time.tv_nsec = 111500000; | |
time_since_start(time_since, sizeof(time_since), cur_time); | |
printf("%s\n", time_since); // prints 0.112 | |
cur_time.tv_sec = 0; | |
cur_time.tv_nsec = 111550000; | |
time_since_start(time_since, sizeof(time_since), cur_time); | |
printf("%s\n", time_since); // prints 0.112 | |
clock_gettime(CLOCK_MONOTONIC, &cur_time); | |
printf("%lld %ld\n", (long long)cur_time.tv_sec, cur_time.tv_nsec); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment