Initial commit
All checks were successful
CI / build-and-analyze (push) Successful in 33s

This commit is contained in:
2026-08-08 20:33:32 +03:00
commit e382d4ed13
12 changed files with 474 additions and 0 deletions

82
posix/Timer.c Normal file
View File

@@ -0,0 +1,82 @@
#define _POSIX_C_SOURCE 200112L
#include "../CgeTimer.h"
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
enum Type {
TYPE_UNDEFINED,
TYPE_OLD_REALTIME,
TYPE_NEW_REALTIME,
TYPE_MONOTONIC
};
static int timerType = TYPE_UNDEFINED;
static int checkAvailableTimer(void) {
#if (_POSIX_TIMERS > 0)
struct timespec ts;
#endif
if (timerType != TYPE_UNDEFINED)
return timerType;
#if (_POSIX_TIMERS > 0)
if (!clock_gettime(CLOCK_MONOTONIC, &ts)) {
timerType = TYPE_MONOTONIC;
} else if (!clock_gettime(CLOCK_REALTIME, &ts)) {
timerType = TYPE_NEW_REALTIME;
} else
#endif
timerType = TYPE_OLD_REALTIME;
return timerType;
}
static void getTimer(uint64_t *sec, uint64_t *nsec) {
#if (_POSIX_TIMERS > 0)
struct timespec ts;
#endif
struct timeval tv;
switch (checkAvailableTimer()) {
#if (_POSIX_TIMERS > 0)
case TYPE_MONOTONIC:
clock_gettime(CLOCK_MONOTONIC, &ts);
*sec = ts.tv_sec;
*nsec = ts.tv_nsec;
break;
case TYPE_NEW_REALTIME:
clock_gettime(CLOCK_REALTIME, &ts);
*sec = ts.tv_sec;
*nsec = ts.tv_nsec;
break;
#endif
default:
case TYPE_OLD_REALTIME:
gettimeofday(&tv, NULL);
*sec = tv.tv_sec;
*nsec = tv.tv_usec * (uint64_t)1000;
break;
}
}
int CgeTimerIsMonotonic(void) {
return checkAvailableTimer() == TYPE_MONOTONIC;
}
uint64_t CgeTimerMilliseconds(void) {
uint64_t newSec, newNsec;
getTimer(&newSec, &newNsec);
return (newSec * 1000u) + (newNsec / 1000000ul);
}
uint64_t CgeTimerNanoseconds(void) {
uint64_t newSec, newNsec;
getTimer(&newSec, &newNsec);
return (newSec * 1000000000ul) + newNsec;
}