blob: d3c25b57ad9fa39bb053366ebc2b3d4cd0d0f568 (
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 NANOS * ((uint64_t) a.tv_sec - b.tv_sec) + ((int64_t) 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;
}
|