summaryrefslogtreecommitdiff
path: root/common/src/timestamp.cpp
blob: 4760816c52b9d0450fa7b3bff1f5742f2ea3d902 (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
#include <time.h>
#include <stdlib.h>

#include "log.h"
#include "timestamp.h"

// 1  s = 1000 ms
// 1 ms = 1000 us
// 1 us = 1000 ns

struct timestamp
{
    uint64_t timestamp_ms;
    uint64_t update_interval_ms;
};

struct timestamp *timestamp_new(uint64_t update_interval_ms)
{
    struct timestamp *ts = (struct timestamp *)calloc(1, sizeof(struct timestamp));
    ts->update_interval_ms = update_interval_ms;

    timestamp_update(ts);
    LOG_DEBUG("%s: TIMESTAMP->update_interval_ms : %lu", LOG_TAG_TIMESTAMP, timestamp_update_interval_ms(ts));
    LOG_DEBUG("%s: TIMESTAMP->current_msec       : %lu", LOG_TAG_TIMESTAMP, timestamp_get_msec(ts));

    return ts;
}

void timestamp_free(struct timestamp *ts)
{
    if (ts)
    {
        free(ts);
        ts = NULL;
    }
}

void timestamp_update(struct timestamp *ts)
{
    struct timespec temp;
    clock_gettime(CLOCK_MONOTONIC, &temp);
    uint64_t current_timestamp_ms = temp.tv_sec * 1000 + temp.tv_nsec / 1000000;

    ATOMIC_SET(&ts->timestamp_ms, current_timestamp_ms);
}

uint64_t timestamp_update_interval_ms(struct timestamp *ts)
{
    return ts->update_interval_ms;
}

uint64_t timestamp_get_msec(struct timestamp *ts)
{
    return ATOMIC_READ(&ts->timestamp_ms);
}