ni_nitdoc: added fast copy past utility to signatures.
[nit.git] / lib / realtime.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2012 Alexis Laferrière <alexis.laf@xymus.net>
4 #
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
11 # another product.
12
13 # Provides the Clock utility class to keep time of real time flow
14 module realtime
15
16 in "C header" `{
17 #ifdef _POSIX_C_SOURCE
18 #undef _POSIX_C_SOURCE
19 #endif
20 #define _POSIX_C_SOURCE 199309L
21 #include <time.h>
22 `}
23
24 extern 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;
28 return tv;
29 `}
30 new monotonic_now `{
31 struct timespec* tv = malloc( sizeof(struct timespec) );
32 clock_gettime( CLOCK_MONOTONIC, tv );
33 return tv;
34 `}
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;
39 return tv;
40 `}
41
42 fun update `{
43 clock_gettime( CLOCK_MONOTONIC, recv );
44 `}
45 fun - ( o : Timespec ) : Timespec
46 do
47 var s = sec - o.sec
48 var ns = nanosec - o.nanosec
49 if ns > nanosec then s += 1
50 return new Timespec( s, ns )
51 end
52
53 fun sec : Int `{
54 return recv->tv_sec;
55 `}
56 fun nanosec : Int `{
57 return recv->tv_nsec;
58 `}
59
60 fun destroy `{
61 free( recv );
62 `}
63 end
64
65 # Keeps track of real time
66 class Clock
67 # Time at instanciation
68 protected var time_at_beginning : Timespec
69
70 # Time at last time a lapse method was called
71 protected var time_at_last_lapse : Timespec
72
73 init
74 do
75 time_at_beginning = new Timespec.monotonic_now
76 time_at_last_lapse = new Timespec.monotonic_now
77 end
78
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 );
83 return tv;
84 `}
85
86 # Return timelapse since instanciation of this instance
87 fun total : Timespec
88 do
89 return new Timespec.monotonic_now - time_at_beginning
90 end
91
92 # Return timelapse since last call to lapse
93 fun lapse : Timespec
94 do
95 var nt = new Timespec.monotonic_now
96 var dt = nt - time_at_last_lapse
97 time_at_last_lapse = nt
98 return dt
99 end
100 end