master ohmu/fastfetch-openbsd / src / common / time.h
ohmu  ·  2026-10-15
 1#pragma once
 2
 3#include <stdbool.h>
 4#include <stdint.h>
 5#include <time.h>
 6#ifdef _WIN32
 7    #include <ntstatus.h>
 8    #include "common/windows/nt.h"
 9    #include <profileapi.h>
10#elif defined(__HAIKU__)
11    #include <OS.h>
12#endif
13
14#include "common/arrutil.h"
15
16static inline double ffTimeGetTick(void) // In msec
17{
18#ifdef _WIN32
19    extern double ffQpcMultiplier;
20    LARGE_INTEGER start;
21    RtlQueryPerformanceCounter(&start);
22    return (double) start.QuadPart * ffQpcMultiplier;
23#elif defined(__HAIKU__)
24    return (double) system_time() / 1000.;
25#else
26    struct timespec timeNow;
27    clock_gettime(CLOCK_MONOTONIC, &timeNow);
28    return (double) timeNow.tv_sec * 1000. + (double) timeNow.tv_nsec / 1000000.;
29#endif
30}
31
32#if _WIN32
33static inline uint64_t ffFileTimeToUnixMs(uint64_t value) {
34    if (__builtin_expect(__builtin_usubll_overflow(value, 116444736000000000ull, &value), false)) {
35        return 0;
36    }
37    return value / 10000ull;
38}
39#endif
40
41static inline uint64_t ffTimeGetNow(void) {
42#ifdef _WIN32
43    uint64_t timeNow = ffKSystemTimeToUInt64(&SharedUserData->SystemTime);
44    return ffFileTimeToUnixMs((uint64_t) timeNow);
45#elif defined(__HAIKU__)
46    return (uint64_t) real_time_clock_usecs() / 1000u;
47#else
48    struct timespec timeNow;
49    clock_gettime(CLOCK_REALTIME, &timeNow);
50    return (uint64_t) (((uint64_t) timeNow.tv_sec * 1000u) + ((uint64_t) timeNow.tv_nsec / 1000000u));
51#endif
52}
53
54// Returns true if not interrupted
55static inline bool ffTimeSleep(uint32_t msec) {
56#ifdef _WIN32
57    LARGE_INTEGER interval;
58    interval.QuadPart = -(int64_t) msec * 10000; // Relative time in 100-nanosecond intervals
59    return NT_SUCCESS(NtDelayExecution(TRUE, &interval));
60#else
61    return nanosleep(&(struct timespec) { msec / 1000, (long) (msec % 1000) * 1000000 }, nullptr) == 0;
62#endif
63}
64
65// Not thread-safe
66const char* ffTimeToFullStr(uint64_t msec);
67
68// Not thread-safe
69const char* ffTimeToShortStr(uint64_t msec);
70
71// Not thread-safe
72const char* ffTimeToTimeStr(uint64_t msec);
73
74typedef struct FFTimeGetAgeResult {
75    uint32_t years;
76    uint32_t daysOfYear;
77    double yearsFraction;
78} FFTimeGetAgeResult;
79
80FFTimeGetAgeResult ffTimeGetAge(uint64_t birthMs, uint64_t nowMs);