summaryrefslogtreecommitdiffstats
path: root/src/util/sss_time.c
blob: bd985ab1373421beb713ec35e3036fe71875e302 (plain)
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
   SSSD - time utils

   Copyright (C) Sumit Bose <sbose@redhat.com> 2021

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "util/util.h"

#define TV_TO_US(tv) ((tv).tv_sec * 1000000 + (tv).tv_usec)

uint64_t get_start_time()
{
    struct timeval tv;

    if (gettimeofday(&tv, NULL) != 0) {
        DEBUG(SSSDBG_OP_FAILURE, "gettimeofday failed.\n");
        return 0;
    }

    return TV_TO_US(tv);
}

const char *sss_format_time(uint64_t us)
{
    static char out[128];
    int ret;

    if (us == 0) {
        return "[- unavailable -]";
    }

    ret = snprintf(out, sizeof(out), "[%.3f] milliseconds", (double) us/1000);
    if (ret < 0 || ret >= sizeof(out)) {
        return "[- formatting error -]";
    }

    return out;
}

uint64_t get_spend_time_us(uint64_t st)
{
    struct timeval tv;
    uint64_t time_now;

    if (st == 0) {
        DEBUG(SSSDBG_OP_FAILURE, "Missing start time.\n");
        return 0;
    }

    if (gettimeofday(&tv, NULL) != 0) {
        DEBUG(SSSDBG_OP_FAILURE, "gettimeofday failed.\n");
        return 0;
    }

    time_now = TV_TO_US(tv);

    if (st > time_now) {
        DEBUG(SSSDBG_OP_FAILURE, "Start time in future.\n");
        return 0;
    }

    return time_now - st;
}