Skip to content

Commit edb31ec

Browse files
feat(utils): introduce helpers to calculate wall time
Signed-off-by: Coelacanthus <uwu@coelacanthus.name>
1 parent 5b3633a commit edb31ec

2 files changed

Lines changed: 26 additions & 0 deletions

File tree

utils/lpac/utils.c

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
#include <stdio.h>
77
#include <stdlib.h>
88
#include <string.h>
9+
#include <time.h>
10+
#include <unistd.h>
911

1012
#if defined(_WIN32)
1113
static char *strndup(const char *s, size_t n) {
@@ -165,3 +167,20 @@ char *path_concat(const char *restrict a, const char *restrict b) {
165167
snprintf(fullpath, fullpath_len, "%s/%s", a, b);
166168
return fullpath;
167169
}
170+
171+
inline struct timespec get_current_clock(clockid_t clock_id) {
172+
struct timespec current_time;
173+
clock_gettime(clock_id, &current_time);
174+
return current_time;
175+
}
176+
177+
inline struct timespec get_duration(struct timespec t0, struct timespec t1) {
178+
bool borrow = (t1.tv_nsec < t0.tv_nsec);
179+
struct timespec dur = {.tv_sec = (borrow ? 1e9 : 0) + t1.tv_sec - t0.tv_sec,
180+
.tv_nsec = t1.tv_nsec - t0.tv_nsec - (borrow ? 1 : 0)};
181+
return dur;
182+
}
183+
184+
inline struct timespec get_wall_time(struct timespec wall) {
185+
return get_duration(wall, get_current_clock(CLOCK_MONOTONIC));
186+
}

utils/lpac/utils.h

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
#include <stdlib.h>
1111
#include <string.h>
1212
#include <sys/types.h>
13+
#include <time.h>
1314

1415
#define ENV_HTTP_DRIVER "LPAC_HTTP"
1516
#define ENV_APDU_DRIVER "LPAC_APDU"
@@ -79,3 +80,9 @@ char *remove_suffix(char *restrict str, const char *restrict suffix);
7980
char **merge_array_of_str(char *left[], char *right[]);
8081

8182
char *path_concat(const char *restrict a, const char *restrict b);
83+
84+
struct timespec get_current_clock(clockid_t clock_id);
85+
86+
struct timespec get_duration(struct timespec t0, struct timespec t1);
87+
88+
struct timespec get_wall_time(struct timespec wall);

0 commit comments

Comments
 (0)