aboutsummaryrefslogtreecommitdiff
path: root/timer/include/timer.h
blob: 75ae367ea81b64b484f8216ed9efcce76585b311 (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
#pragma once

#include <stdint.h>

/// A particular point in time.
#ifdef _WIN32
typedef uint64_t time_point;
#else
// Need to macro to make CLOCK_REALTIME available when compiling with ISO C11.
// The constant is only needed in the source file, but the header file needs to
// include time.h too.
#ifndef __USE_POSIX199309
#define __USE_POSIX199309
#endif //
#include <time.h>
typedef struct timespec time_point;
#endif

/// Time elapsed between two time points.
typedef uint64_t time_delta;

/// A high resolution timer.
typedef struct Timer {
  time_point start_time;   ///< The instant the timer was last started.
  time_point last_tick;    ///< The instant the timer was last ticked.
  time_delta running_time; ///< Time elapsed since the timer was last started.
  time_delta delta_time;   ///< Time elapsed since the last tick.
} Timer;

/// Construct a new timer.
Timer timer_make(void);

/// Start the timer.
/// This sets the time point from which time deltas are measured.
/// Calling this multilple times resets the timer.
void timer_start(Timer*);

/// Update the timer's running and delta times.
void timer_tick(Timer*);

/// Advance the timer.
///
/// This is used for simulations that wish control over time. It should not be
/// used together with timer_tick().
///
/// The input time is relative to the timer's start time. Successive calls to
/// this function must use increasing values of time.
void timer_advance(Timer* timer, time_delta t);

/// Get the current time.
time_point time_now(void);

/// Return the time elapsed between two timestamps.
time_delta time_diff(time_point start, time_point end);

/// Return the time elapsed in seconds.
double time_delta_to_sec(time_delta dt);

/// Convert the time elapsed in seconds to a time delta.
time_delta sec_to_time_delta(double seconds);

/// Convert the time point to nanoseconds.
uint64_t time_point_to_ns(time_point);

/// Add a time delta to a timestamp.
time_point time_add(time_point, time_delta);

/// Put the caller thread to sleep for the given amount of time.
void time_sleep(time_delta dt);

/// The time point 0.
#ifdef _WIN32
static const time_point time_zero = 0;
#else
static const time_point time_zero = {0, 0};
#endif