ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
time.h
Go to the documentation of this file.
1#pragma once
3
5
38
39/* Storage capacities in elements; text buffers include the terminating NUL. */
40#define TIME_DURATION_BUFFER_SIZE 32
41
42/* Storage capacities in elements; text buffers include the terminating NUL. */
43#define UTIL_TIME_TIMER_NAME_BUFFER_SIZE 256
44#define UTIL_TIME_TIMER_NAME_WITH_TID_BUFFER_SIZE 280
45
46#include <stdint.h>
47#include <stdbool.h>
48#include <time.h>
49#include <libplatform/time.h>
50// C11 stdatomic.h conflicts with MSVC's C++ <atomic> header on Windows.
51// Include the appropriate header based on the compilation mode.
52#if defined(__cplusplus) && defined(_WIN32)
53#include <atomic>
54using std::atomic_compare_exchange_weak_explicit;
55using std::atomic_load_explicit;
56using std::memory_order_relaxed;
57// C11 _Atomic(T) syntax doesn't work in C++ - use std::atomic<T> instead
58#define TIME_ATOMIC_UINT64 std::atomic<uint64_t>
59#define TIME_ATOMIC_UINT64_INIT(val) {val}
60#else
61#include <libplatform/atomic.h>
62// Use atomic_t for rate-limiting counters
63#define TIME_ATOMIC_UINT64 atomic_t
64#define TIME_ATOMIC_UINT64_INIT(val) {0}
65#endif
66
67// ============================================================================
68// sokol_time.h Integration
69// ============================================================================
70
71// Include sokol_time.h declarations (WITHOUT implementation)
72// SOKOL_TIME_IMPL is defined only in time.c to avoid duplicate symbols
73#include <ascii-chat-deps/sokol/sokol_time.h>
74
75// Include platform thread for thread ID in timer names
76#include <libplatform/thread.h>
77
78// Include uthash wrapper for UBSan-safe hash functions
79// Headers can include this even before common.h is fully processed
80#include <ascii-chat/uthash.h>
81
82#ifdef __cplusplus
83extern "C" {
84#endif
85
86// ============================================================================
87// Core Monotonic Timing API (Nanosecond Precision)
88// ============================================================================
89
109
123
134void time_sleep_ns(uint64_t ns);
135
155uint64_t time_elapsed_ns(uint64_t start_ns, uint64_t end_ns);
156
157// ============================================================================
158// Time Unit Constants (moved before inline functions that use them)
159// ============================================================================
160
161// Floating-point versions (for time formatting and conversions)
162#define NS_PER_US 1000.0
163#define NS_PER_MS (1000.0 * NS_PER_US)
164#define NS_PER_SEC (1000.0 * NS_PER_MS)
165#define NS_PER_MIN (60.0 * NS_PER_SEC)
166#define NS_PER_HOUR (60.0 * NS_PER_MIN)
167#define NS_PER_DAY (24.0 * NS_PER_HOUR)
168#define NS_PER_YEAR (365.25 * NS_PER_DAY) // Account for leap years
169
170// Integer versions (for comparing uint64_t nanosecond values)
171#define NS_PER_US_INT 1000ULL
172#define NS_PER_MS_INT (1000ULL * NS_PER_US_INT)
173#define NS_PER_SEC_INT (1000ULL * NS_PER_MS_INT)
174
175// Microsecond versions (for API compatibility)
176#define US_PER_MS_INT 1000ULL
177#define US_PER_SEC_INT 1000000ULL
178
179// Millisecond versions (for API compatibility)
180#define MS_PER_SEC_INT 1000ULL
181
182// Standard time unit conversions (seconds-based)
183#define SEC_PER_MIN 60ULL
184#define SEC_PER_HOUR (SEC_PER_MIN * SEC_PER_MIN)
185#define SEC_PER_DAY (24ULL * SEC_PER_HOUR)
186
187// Minute/hour/day to nanoseconds conversions
188#define NS_PER_MIN_INT (SEC_PER_MIN * NS_PER_SEC_INT)
189#define NS_PER_HOUR_INT (SEC_PER_HOUR * NS_PER_SEC_INT)
190#define NS_PER_DAY_INT (SEC_PER_DAY * NS_PER_SEC_INT)
191
192// ============================================================================
193// Inline Time Conversion Helpers
194// ============================================================================
195
202static inline uint64_t time_ns_to_us(uint64_t ns) {
203 return ns / NS_PER_US_INT;
204}
205
212static inline uint64_t time_ns_to_ms(uint64_t ns) {
213 return ns / NS_PER_MS_INT;
214}
215
222static inline double time_ns_to_s(uint64_t ns) {
223 return (double)ns / 1e9;
224}
225
232static inline uint64_t time_us_to_ns(uint64_t us) {
233 return us * NS_PER_US_INT;
234}
235
242static inline uint64_t time_ms_to_ns(uint64_t ms) {
243 return ms * NS_PER_MS_INT;
244}
245
252static inline uint64_t time_s_to_ns(double s) {
253 return (uint64_t)(s * 1e9);
254}
255
256// ============================================================================
257// Timer Record Structure
258// ============================================================================
259
264typedef struct timer_record {
265 char *name;
267 UT_hash_handle hh;
269
270// ============================================================================
271// Timer System API
272// ============================================================================
273
283bool timer_system_init(void);
284
293void timer_system_destroy(void);
294
305bool timer_start(const char *name);
306
317double timer_stop(const char *name);
318double timer_stop_formatted(const char *name_fmt, ...);
319
326bool timer_is_initialized(void);
327
328// ============================================================================
329// Convenience Macros
330// ============================================================================
331
350#define START_TIMER(name_fmt, ...) \
351 do { \
352 if (timer_is_initialized()) { \
353 char _timer_name_buf[UTIL_TIME_TIMER_NAME_BUFFER_SIZE]; \
354 char _timer_name_with_tid[UTIL_TIME_TIMER_NAME_WITH_TID_BUFFER_SIZE]; \
355 snprintf(_timer_name_buf, sizeof(_timer_name_buf), name_fmt, ##__VA_ARGS__); \
356 snprintf(_timer_name_with_tid, sizeof(_timer_name_with_tid), "%s_tid%llu", _timer_name_buf, (unsigned long long)thread_current_id()); \
357 (void)timer_start(_timer_name_with_tid); \
358 } \
359 } while (asciichat_macro_block_continue())
360
373#define START_TIMER_GLOBAL(name_fmt, ...) \
374 do { \
375 if (timer_is_initialized()) { \
376 char _timer_name_buf[UTIL_TIME_TIMER_NAME_BUFFER_SIZE]; \
377 snprintf(_timer_name_buf, sizeof(_timer_name_buf), name_fmt, ##__VA_ARGS__); \
378 (void)timer_start(_timer_name_buf); \
379 } \
380 } while (asciichat_macro_block_continue())
381
393#define STOP_TIMER_GLOBAL(name_fmt, ...) \
394 ({ \
395 double _elapsed = -1.0; \
396 if (timer_is_initialized()) { \
397 char _timer_name_buf[UTIL_TIME_TIMER_NAME_BUFFER_SIZE]; \
398 snprintf(_timer_name_buf, sizeof(_timer_name_buf), name_fmt, ##__VA_ARGS__); \
399 _elapsed = timer_stop(_timer_name_buf); \
400 } \
401 _elapsed; \
402 })
403
419#define STOP_TIMER(name_fmt, ...) timer_stop_formatted(name_fmt, ##__VA_ARGS__)
420
421// ============================================================================
422// Time Formatting API
423// ============================================================================
424
462int time_pretty(uint64_t nanoseconds, int decimals, char *buffer, size_t buffer_size);
463
479int time_pretty_now(int decimals, char *buffer, size_t buffer_size);
480
529int time_human_readable(int64_t nanoseconds, char *buffer, size_t buffer_size);
530
552int time_human_readable_unsigned(uint64_t nanoseconds, char *buffer, size_t buffer_size);
553
568int time_human_readable_now(char *buffer, size_t buffer_size);
569
594int format_uptime_hms(int hours, int minutes, int seconds, char *buffer, size_t buffer_size);
595
618#define STOP_TIMER_AND_LOG(log_level, threshold_ns, timer_name, msg_fmt, ...) \
619 do { \
620 double _elapsed_ns = STOP_TIMER(timer_name, ##__VA_ARGS__); \
621 if (_elapsed_ns >= 0.0 && (threshold_ns == 0 || _elapsed_ns >= (double)(threshold_ns))) { \
622 char _duration_str[TIME_DURATION_BUFFER_SIZE]; \
623 time_pretty((uint64_t)_elapsed_ns, -1, _duration_str, sizeof(_duration_str)); \
624 log_##log_level(msg_fmt " in %s", ##__VA_ARGS__, _duration_str); \
625 } \
626 } while (asciichat_macro_block_continue())
627
653#define STOP_TIMER_AND_LOG_EVERY(log_level, interval_ns, threshold_ns, timer_name, msg_fmt, ...) \
654 do { \
655 double _elapsed_ns = STOP_TIMER(timer_name, ##__VA_ARGS__); \
656 if (_elapsed_ns >= 0.0 && (threshold_ns == 0 || _elapsed_ns >= (double)(threshold_ns))) { \
657 static atomic_t _log_every_last_time = {0}; \
658 uint64_t _log_every_now = time_get_ns(); \
659 uint64_t _log_every_last = atomic_load_u64(&_log_every_last_time); \
660 if (_log_every_now - _log_every_last >= (uint64_t)(interval_ns)) { \
661 if (atomic_cas_u64(&_log_every_last_time, &_log_every_last, _log_every_now)) { \
662 char _duration_str[TIME_DURATION_BUFFER_SIZE]; \
663 time_pretty((uint64_t)_elapsed_ns, -1, _duration_str, sizeof(_duration_str)); \
664 log_##log_level(msg_fmt " in %s", ##__VA_ARGS__, _duration_str); \
665 } \
666 } \
667 } \
668 } while (asciichat_macro_block_continue())
669
670// ============================================================================
671// Adaptive Sleep System
672// ============================================================================
673
690
704
717
757uint64_t adaptive_sleep_calculate(adaptive_sleep_state_t *state, size_t queue_depth, size_t target_depth);
758
770void adaptive_sleep_do(adaptive_sleep_state_t *state, size_t queue_depth, size_t target_depth);
771
772/* ============================================================================
773 * Time Format Validation and Formatting
774 * ============================================================================ */
775
800bool time_format_is_valid_strftime(const char *format_str);
801
826int time_format_now(const char *format_str, char *buf, size_t buf_size);
827
857asciichat_error_t time_format_safe(const char *format_str, char *buf, size_t buf_size);
858
860
861/* ============================================================================
862 * Conversion Functions
863 * ============================================================================ */
864
873uint64_t time_timespec_to_ns(const struct timespec *ts);
874
883
884#ifdef __cplusplus
885}
886#endif
Synchronized per-thread pending error stacks and value snapshots. SET_ERRNO pushes,...
int buffer_size
Size of circular buffer.
Definition grep.c:69
unsigned long long uint64_t
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
double timer_stop_formatted(const char *name_fmt,...)
Definition time.c:324
double timer_stop(const char *name)
Stop a named timer and return elapsed time.
Definition time.c:268
int time_pretty_now(int decimals, char *buffer, size_t buffer_size)
Format current monotonic time as pretty duration.
Definition time.c:515
bool timer_start(const char *name)
Start a named timer.
Definition time.c:214
bool time_format_is_valid_strftime(const char *format_str)
Validate strftime format string against known safe specifiers.
Definition time.c:698
uint64_t adaptive_sleep_calculate(adaptive_sleep_state_t *state, size_t queue_depth, size_t target_depth)
Calculate adaptive sleep time based on queue depth.
Definition time.c:611
int time_pretty(uint64_t nanoseconds, int decimals, char *buffer, size_t buffer_size)
Format nanoseconds as a compact duration with configurable sub-minute precision.
Definition time.c:406
int time_format_now(const char *format_str, char *buf, size_t buf_size)
Format current time using strftime format string.
Definition time.c:778
uint64_t time_timespec_to_ns(const struct timespec *ts)
Convert struct timespec to nanoseconds.
Definition time.c:141
void timer_system_destroy(void)
Cleanup the timing system.
Definition time.c:187
#define NS_PER_MS_INT
Definition time.h:172
int time_human_readable_unsigned(uint64_t nanoseconds, char *buffer, size_t buffer_size)
Format elapsed time as human-readable relative duration (unsigned version).
Definition time.c:524
void adaptive_sleep_init(adaptive_sleep_state_t *state, const adaptive_sleep_config_t *config)
Initialize adaptive sleep state with configuration.
Definition time.c:588
int time_human_readable(int64_t nanoseconds, char *buffer, size_t buffer_size)
Format nanoseconds as human-readable relative duration (moment.js style).
Definition time.c:549
uint64_t time_elapsed_ns(uint64_t start_ns, uint64_t end_ns)
Calculate elapsed time with wraparound safety.
Definition time.c:126
#define NS_PER_US_INT
Definition time.h:171
int format_uptime_hms(int hours, int minutes, int seconds, char *buffer, size_t buffer_size)
Format uptime as HH:MM:SS string.
Definition time.c:346
void time_sleep_ns(uint64_t ns)
Configuration for adaptive sleep behavior.
Definition time.c:116
bool timer_is_initialized(void)
Check if timing system is initialized.
Definition time.c:338
bool timer_system_init(void)
Initialize the timing system.
Definition time.c:164
void adaptive_sleep_do(adaptive_sleep_state_t *state, size_t queue_depth, size_t target_depth)
Calculate sleep time and immediately sleep for that duration.
Definition time.c:677
struct timer_record timer_record_t
Individual timer record for a named timing operation.
asciichat_error_t time_format_safe(const char *format_str, char *buf, size_t buf_size)
Safe wrapper for time formatting with validation and error codes.
Definition time.c:818
int time_human_readable_now(char *buffer, size_t buffer_size)
Format current monotonic time as human-readable relative duration.
Definition time.c:579
Configuration for adaptive sleep behavior.
Definition time.h:683
double min_speed_multiplier
Minimum speed (max sleep) - usually 1.0 (baseline speed).
Definition time.h:685
double max_speed_multiplier
Maximum speed (min sleep) - e.g., 4.0 = process 4x faster.
Definition time.h:686
uint64_t baseline_sleep_ns
Normal sleep time in nanoseconds (when queue is at target).
Definition time.h:684
double speedup_rate
Ramp-up rate when queue builds (0.0-1.0, higher = faster ramp).
Definition time.h:687
double slowdown_rate
Ramp-down rate when queue empties (0.0-1.0, higher = faster ramp).
Definition time.h:688
Runtime state for adaptive sleep.
Definition time.h:699
double current_speed_multiplier
Current speed state (1.0 = baseline, >1.0 = faster).
Definition time.h:701
uint64_t last_sleep_ns
Last calculated sleep time (for debugging).
Definition time.h:702
adaptive_sleep_config_t config
Configuration (copied, not referenced).
Definition time.h:700
Individual timer record for a named timing operation.
Definition time.h:264
uint64_t start_ticks
Start time in sokol ticks.
Definition time.h:266
char * name
Timer name (heap-allocated, unique key).
Definition time.h:265
UT_hash_handle hh
uthash handle (makes this hashable by name)
Definition time.h:267
⏱️ High-precision timing utilities using sokol_time.h and uthash