blob: c0d7df936fc58df9e6ef803bb24743fe40034dde (
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
|
// SPDX-FileCopyrightText: 2024 Lizzy Fleckenstein <lizzy@vlhl.dev>
//
// SPDX-License-Identifier: AGPL-3.0-or-later
#include "ticker.h"
static struct timespec timestamp_now()
{
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts); // TODO: handle error
return ts;
}
static uint64_t timestamp_diff(struct timespec a, struct timespec b)
{
return ((uint64_t) a.tv_sec - b.tv_sec) * NANOS + a.tv_nsec - b.tv_nsec;
}
void ticker_init(ticker *t, uint64_t f)
{
t->freq_nanos = f;
t->timestamp = timestamp_now();
}
bool ticker_tick(ticker *t, uint64_t *dtime)
{
struct timespec ts = timestamp_now();
*dtime = timestamp_diff(ts, t->timestamp);
if (*dtime < t->freq_nanos)
return false;
t->timestamp = ts;
return true;
}
// millis
int ticker_timeout(ticker *t)
{
uint64_t nanos = timestamp_diff(timestamp_now(), t->timestamp);
if (t->freq_nanos > nanos)
return (t->freq_nanos - nanos) / 1000000; // nanos to millis
else
return 0;
}
|