added gettime and sleep functions
This commit is contained in:
parent
f5805888bc
commit
d3a8c03fe5
30
include/tlibc/time.h
Normal file
30
include/tlibc/time.h
Normal file
@ -0,0 +1,30 @@
|
||||
#pragma once
|
||||
|
||||
#if __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#include "std.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
|
||||
46
src/time.c
Normal file
46
src/time.c
Normal file
@ -0,0 +1,46 @@
|
||||
// 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 "tlibc/time.h"
|
||||
#include <time.h>
|
||||
#include <assert.h>
|
||||
|
||||
#define K 1000
|
||||
#define M 1000000
|
||||
#define G 1000000000
|
||||
|
||||
nsec_t getTimeNsec(){
|
||||
struct timespec t;
|
||||
assert(clock_gettime(CLOCK_REALTIME, &t) != 0);
|
||||
u64 n = t.tv_sec * G + t.tv_nsec;
|
||||
return n;
|
||||
}
|
||||
|
||||
usec_t getTimeUsec(){
|
||||
struct timespec t;
|
||||
assert(clock_gettime(CLOCK_REALTIME, &t) != 0);
|
||||
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
|
||||
};
|
||||
assert(nanosleep(&t, NULL) != 0);
|
||||
}
|
||||
|
||||
void sleepUsec(usec_t time){
|
||||
sleepNsec(time * K);
|
||||
}
|
||||
|
||||
void sleepMsec(msec_t time){
|
||||
sleepNsec(time * M);
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user