aboutsummaryrefslogtreecommitdiff
path: root/include/time_utils.h
blob: f80e1162def66dc27fa4c65f6e31c30a18e70695 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/* SPDX-License-Identifier: Apache-2.0 */

/* Copyright 2025 Thorsten Töpper
 * vim:ts=4:sw=4:expandtab
 */
#ifndef TIME_UTILS_H
#define TIME_UTILS_H

#include <time.h>

#define TU_MEASURE_TIME(clck, ts1, ts2, code) \
    clock_gettime(clck, ts1); \
    code \
    clock_gettime(clck, ts2);

int difftime_timespec(struct timespec ts1, struct timespec ts2, struct timespec *result);


inline int difftime_timespec(struct timespec ts1, struct timespec ts2, struct timespec *result) {
    if (result == NULL)
        return -1;
    result->tv_sec = 0;
    result->tv_nsec = 0;

    if (ts1.tv_sec > ts2.tv_sec ||
        ( (ts1.tv_sec == ts2.tv_sec) && ts1.tv_nsec > ts2.tv_nsec))
        return -2;

    result->tv_sec = ts2.tv_sec - ts1.tv_sec;

    if (ts1.tv_nsec > ts2.tv_nsec) {
        result->tv_nsec = (ts2.tv_nsec+1000000000) - ts1.tv_nsec;
    } else {
        result->tv_nsec = ts2.tv_nsec - ts1.tv_nsec;
    }
    return 0;
}

#endif