// ntime.c // PUBLIC DOMAIN // http:///www.purposeful.co.uk/software/yabaplib /* I, Tom Vajzovic, am the author of this software and its documentation. I permanently abandon all intellectual property rights in them, including copyright, trademarks, design rights, database right, patents, and the right to be identified as the author. I am fairly certain that the software does what the documentation says it does, but I do not guarantee that it does, or that it does what you think it should. I do not guarantee that it will not have undesirable side effects. You are free to use, modify and distribute this software as you please, but you do so at your own risk. If you do not pass on this warning then you may be responsible for any problems encountered by those who obtain the software through you. */ #include #include #include #include #include #include #include "ntime.h" #define US_PER_NS 1000u #define US_PER_SECOND 1000000u #define NS_PER_SECOND 1000000000u void nsleep(uint64_t delay_nanoseconds) { #if defined (_POSIX_TIMERS) && (_POSIX_TIMERS > 0) && defined (_POSIX_MONOTONIC_CLOCK) && (_POSIX_MONOTONIC_CLOCK > 0) struct timespec finish; if (clock_gettime(CLOCK_MONOTONIC, &finish) == 0) { uint64_t finish_ns = (delay_nanoseconds + (uint64_t)finish.tv_nsec); if (delay_nanoseconds > (UINT64_MAX - (uint64_t)finish.tv_nsec)) // did the addition wrap? { finish.tv_sec++; finish_ns -= NS_PER_SECOND; // unwrap } finish.tv_sec += (finish_ns / NS_PER_SECOND); finish.tv_nsec = (finish_ns % NS_PER_SECOND); while (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &finish, NULL)); } else { #endif struct timespec request = {(delay_nanoseconds / NS_PER_SECOND), (delay_nanoseconds % NS_PER_SECOND)}; struct timespec remainder; while (nanosleep(&request, &remainder)) { request = remainder; } #if defined (_POSIX_TIMERS) && (_POSIX_TIMERS > 0) && defined (_POSIX_MONOTONIC_CLOCK) && (_POSIX_MONOTONIC_CLOCK > 0) } #endif } int64_t ntime( void ){ #if defined (_POSIX_TIMERS) && (_POSIX_TIMERS > 0) { struct timespec tp; if( ! clock_gettime( CLOCK_REALTIME, & tp )) return ((int64_t)NS_PER_SECOND * tp. tv_sec) + tp. tv_nsec; } #endif /* _POSIX_TIMERS */ { struct timeval tv; if( ! gettimeofday( & tv, NULL )) return (((int64_t)US_PER_SECOND * tv. tv_sec) + tv. tv_usec) * US_PER_NS; } { int save_errno= errno; time_t t; errno= 0; t= time( NULL ); if( -1 == t && errno ) return -1; errno= save_errno; return (int64_t)NS_PER_SECOND * t; } } #if defined (_POSIX_MONOTONIC_CLOCK) && (_POSIX_MONOTONIC_CLOCK > 0) uint64_t ntime_mono( void ){ struct timespec tp; if( clock_gettime( CLOCK_MONOTONIC, & tp )) return 0; return NS_PER_SECOND * (uint64_t) tp. tv_sec + (uint64_t) tp. tv_nsec; } #else /* _POSIX_MONOTONIC_CLOCK */ uint64_t ntime_mono( void ){ int64_t t= ntime(); return 0 > t ? 0 : t; } #endif /* _POSIX_MONOTONIC_CLOCK */