1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2012 Alexis Laferrière <alexis.laf@xymus.net>
5 # This file is free software, which comes along with NIT. This software is
6 # distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
7 # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
8 # PARTICULAR PURPOSE. You can modify it is you want, provided this header
9 # is kept unaltered, and a notification of the changes is added.
10 # You are allowed to redistribute it and sell it, alone or is a part of
13 # Provides the Clock utility class to keep time of real time flow
14 module realtime
is ldflags
"-lrt"
17 #ifdef _POSIX_C_SOURCE
18 #undef _POSIX_C_SOURCE
20 #define _POSIX_C_SOURCE 199309L
24 # Elapsed time representation.
25 extern class Timespec `{struct timespec*`}
27 # Init a new Timespec from `s
` seconds and `ns
` nanoseconds.
28 new ( s, ns : Int ) `{
29 struct timespec
* tv
= malloc
( sizeof
(struct timespec
) );
30 tv-
>tv_sec
= s
; tv-
>tv_nsec
= ns
;
34 # Init a new Timespec from now.
36 struct timespec
* tv
= malloc
( sizeof
(struct timespec
) );
37 clock_gettime
( CLOCK_MONOTONIC, tv
);
41 # Init a new Timespec copied from another.
42 new copy_of( other : Timespec ) `{
43 struct timespec
* tv
= malloc
( sizeof
(struct timespec
) );
44 tv-
>tv_sec
= other-
>tv_sec
;
45 tv-
>tv_nsec
= other-
>tv_nsec
;
49 # Update `self` clock.
51 clock_gettime
( CLOCK_MONOTONIC, recv
);
54 # Substract a Timespec from `self`.
55 fun - ( o : Timespec ) : Timespec
58 var ns = nanosec - o.nanosec
59 if ns > nanosec then s += 1
60 return new Timespec( s, ns )
63 # Number of whole seconds of elapsed time.
68 # Rest of the elapsed time (a fraction of a second).
70 # Number of nanoseconds.
76 # Loss of precision but great to print
77 fun to_f: Float do return sec.to_f + nanosec.to_f / 1000000000.0
79 redef fun to_s do return "{to_f}s"
82 # Keeps track of real time
84 # Time at instanciation
85 protected var time_at_beginning = new Timespec.monotonic_now
87 # Time at last time a lapse method was called
88 protected var time_at_last_lapse = new Timespec.monotonic_now
90 # Smallest time frame reported by clock
91 fun resolution : Timespec `{
92 struct timespec
* tv
= malloc
( sizeof
(struct timespec
) );
93 clock_getres
( CLOCK_MONOTONIC, tv
);
97 # Return timelapse since instanciation of this instance
100 return new Timespec.monotonic_now - time_at_beginning
103 # Return timelapse since last call to lapse
106 var nt = new Timespec.monotonic_now
107 var dt = nt - time_at_last_lapse
108 time_at_last_lapse = nt