X-Git-Url: http://nitlanguage.org diff --git a/lib/realtime.nit b/lib/realtime.nit index 5a9571d..a400619 100644 --- a/lib/realtime.nit +++ b/lib/realtime.nit @@ -23,7 +23,7 @@ in "C header" `{ in "C" `{ -#ifdef __MACH__ +#if defined(__MACH__) && !defined(CLOCK_REALTIME) /* OS X does not have clock_gettime, mascarade it and use clock_get_time * cf http://stackoverflow.com/questions/11680461/monotonic-clock-on-osx */ @@ -74,16 +74,17 @@ extern class Timespec `{struct timespec*`} `} # Subtract `other` from `self` - fun -(other: Timespec): Timespec - do - var s = sec - other.sec - var ns = nanosec - other.nanosec - if ns < 0 then - s -= 1 - ns += 1000000000 - end - return new Timespec(s, ns) - end + fun -(other: Timespec): Timespec `{ + time_t s = self->tv_sec - other->tv_sec; + long ns = self->tv_nsec - other->tv_nsec; + if (ns < 0) { + s -= 1; + ns += 1000000000l; + } + struct timespec* tv = malloc(sizeof(struct timespec)); + tv->tv_sec = s; tv->tv_nsec = ns; + return tv; + `} # Number of whole seconds of elapsed time. fun sec : Int `{ @@ -114,12 +115,28 @@ extern class Timespec `{struct timespec*`} # Number of seconds as a `Float` # # Incurs a loss of precision, but the result is pretty to print. - fun to_f: Float do return sec.to_f + nanosec.to_f / 1000000000.0 + fun to_f: Float `{ + return (double)self->tv_sec + 0.000000001 * self->tv_nsec; + `} redef fun to_s do return "{to_f}s" end # Keeps track of real time +# +# ~~~ +# var clock = new Clock +# +# # sleeping at least 1s +# 1.0.sleep +# assert clock.total >= 1.0 +# assert clock.lapse >= 1.0 +# +# # sleeping at least 5ms +# 0.005.sleep +# assert clock.total >= 1.005 +# assert clock.lapse >= 0.005 +# ~~~ class Clock super FinalizableOnce @@ -134,7 +151,7 @@ class Clock # Smallest time frame reported by clock fun resolution: Timespec `{ struct timespec* tv = malloc( sizeof(struct timespec) ); -#ifdef __MACH__ +#if defined(__MACH__) && !defined(CLOCK_REALTIME) clock_serv_t cclock; int nsecs; mach_msg_type_number_t count;