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 c_linker_option
("-lrt")
17 #ifdef _POSIX_C_SOURCE
18 #undef _POSIX_C_SOURCE
20 #define _POSIX_C_SOURCE 199309L
24 extern class Timespec `{struct timespec*`}
25 new ( s, ns : Int ) `{
26 struct timespec
* tv
= malloc
( sizeof
(struct timespec
) );
27 tv-
>tv_sec
= s
; tv-
>tv_nsec
= ns
;
31 struct timespec
* tv
= malloc
( sizeof
(struct timespec
) );
32 clock_gettime
( CLOCK_MONOTONIC, tv
);
35 new copy_of( other : Timespec ) `{
36 struct timespec
* tv
= malloc
( sizeof
(struct timespec
) );
37 tv-
>tv_sec
= other-
>tv_sec
;
38 tv-
>tv_nsec
= other-
>tv_nsec
;
43 clock_gettime
( CLOCK_MONOTONIC, recv
);
45 fun - ( o : Timespec ) : Timespec
48 var ns = nanosec - o.nanosec
49 if ns > nanosec then s += 1
50 return new Timespec( s, ns )
65 # Keeps track of real time
67 # Time at instanciation
68 protected var time_at_beginning : Timespec
70 # Time at last time a lapse method was called
71 protected var time_at_last_lapse : Timespec
75 time_at_beginning = new Timespec.monotonic_now
76 time_at_last_lapse = new Timespec.monotonic_now
79 # Smallest time frame reported by clock
80 fun resolution : Timespec `{
81 struct timespec
* tv
= malloc
( sizeof
(struct timespec
) );
82 clock_getres
( CLOCK_MONOTONIC, tv
);
86 # Return timelapse since instanciation of this instance
89 return new Timespec.monotonic_now - time_at_beginning
92 # Return timelapse since last call to lapse
95 var nt = new Timespec.monotonic_now
96 var dt = nt - time_at_last_lapse
97 time_at_last_lapse = nt