Created
May 11, 2020 11:55
-
-
Save hnakamur/4246f57ee0d1eaa3224e40a46620c56b to your computer and use it in GitHub Desktop.
try to print time on every second on realtime clock
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
#include <errno.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <time.h> | |
const int sec_in_nsec = 1000000000; | |
#define ITERMAX 10000 | |
typedef long long nanotime_t; | |
// nanotime -- get time in nanoseconds | |
static inline nanotime_t | |
nanotime(clockid_t clk_id) | |
{ | |
struct timespec ts; | |
clock_gettime(clk_id, &ts); | |
return ts.tv_sec * sec_in_nsec + ts.tv_nsec; | |
} | |
static nanotime_t | |
time_for_realtime() | |
{ | |
nanotime_t t0, t1; | |
int i; | |
t0 = nanotime(CLOCK_MONOTONIC); | |
for (i = 0; i < ITERMAX; i++) { | |
nanotime(CLOCK_REALTIME); | |
} | |
t1 = nanotime(CLOCK_MONOTONIC); | |
return (t1 - t0) / ITERMAX; | |
} | |
static nanotime_t | |
time_for_fprintf() | |
{ | |
nanotime_t t0, t1; | |
long t; | |
int i; | |
t = 123; | |
t0 = nanotime(CLOCK_MONOTONIC); | |
for (i = 0; i < ITERMAX; i++) { | |
fprintf(stderr, "%09ld\n", t); | |
} | |
t1 = nanotime(CLOCK_MONOTONIC); | |
return (t1 - t0) / ITERMAX; | |
} | |
int run_timer() { | |
nanotime_t avg = time_for_realtime(); | |
nanotime_t tp = time_for_fprintf(); | |
fprintf(stderr, "avg=%lld\n", avg); | |
fprintf(stderr, "tp=%lld\n", tp); | |
for (;;) { | |
struct timespec ts; | |
int ret = clock_gettime(CLOCK_REALTIME, &ts); | |
if (ret < 0) { | |
fprintf(stderr, "error in clock_gettime: %s\n", strerror(errno)); | |
return 1; | |
} | |
// print just nanosecond for simplicity; | |
fprintf(stderr, "%09ld\n", ts.tv_nsec); | |
ts.tv_sec = 0; | |
ts.tv_nsec = sec_in_nsec - ts.tv_nsec - avg - tp; | |
if (ts.tv_nsec < 0) { | |
ts.tv_nsec += sec_in_nsec; | |
} | |
ret = nanosleep(&ts, NULL); | |
if (ret < 0) { | |
fprintf(stderr, "error in nanosleep: %s\n", strerror(errno)); | |
return 1; | |
} | |
} | |
} | |
int main(int argc, char **argv) { | |
return run_timer(); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment