src/time/

This commit is contained in:
Timerix22 2024-04-09 04:16:59 +05:00
parent da504dfcf5
commit 235889604e
2 changed files with 78 additions and 0 deletions

48
src/time/time.c Normal file
View File

@ -0,0 +1,48 @@
// posix version definition to use clock_gettime
#ifndef _XOPEN_SOURCE
#if __STDC_VERSION__ >= 199901L
#define _XOPEN_SOURCE 600
#else
#define _XOPEN_SOURCE 500
#endif
#endif
#include "time.h"
#include <time.h>
#define K 1000
#define M 1000000
#define G 1000000000
nsec_t getTimeNsec(){
struct timespec t;
if(clock_gettime(CLOCK_REALTIME, &t) != 0)
throw(ERR_UNEXPECTEDVAL);
u64 n = t.tv_sec * G + t.tv_nsec;
return n;
}
usec_t getTimeUsec(){
struct timespec t;
if(clock_gettime(CLOCK_REALTIME, &t) != 0)
throw(ERR_UNEXPECTEDVAL);
u64 n = t.tv_sec * M + t.tv_nsec / K;
return n;
}
void sleepNsec(nsec_t time){
struct timespec t = {
.tv_sec = time / G,
.tv_nsec = time % G
};
if(nanosleep(&t, NULL) != 0)
throw(ERR_UNEXPECTEDVAL);
}
void sleepUsec(usec_t time){
sleepNsec(time * K);
}
void sleepMsec(msec_t time){
sleepNsec(time * M);
}

30
src/time/time.h Normal file
View File

@ -0,0 +1,30 @@
#pragma once
#if __cplusplus
extern "C" {
#endif
#include "../base/base.h"
/// nanoseconds
typedef u64 nsec_t;
/// microseconds
typedef u64 usec_t;
/// miliseconds
typedef u64 msec_t;
/// system time now in nanoseconds
///@return u64 will overflow in 13 years
nsec_t getTimeNsec();
/// system time now in microseconds
///@return u64 will overflow in 58494 years
usec_t getTimeUsec();
void sleepNsec(nsec_t time);
void sleepUsec(usec_t time);
void sleepMsec(msec_t time);
#if __cplusplus
}
#endif