Updated license
[anna.git] / include / anna / timex / Meter.hpp
1 // ANNA - Anna is Not Nothingness Anymore
2 //
3 // (c) Copyright 2005-2014 Eduardo Ramos Testillano & Francisco Ruiz Rayo
4 //
5 // https://bitbucket.org/testillano/anna
6 //
7 // Redistribution and use in source and binary forms, with or without
8 // modification, are permitted provided that the following conditions
9 // are met:
10 //
11 //     * Redistributions of source code must retain the above copyright
12 // notice, this list of conditions and the following disclaimer.
13 //     * Redistributions in binary form must reproduce the above
14 // copyright notice, this list of conditions and the following disclaimer
15 // in the documentation and/or other materials provided with the
16 // distribution.
17 //     * Neither the name of Google Inc. nor the names of its
18 // contributors may be used to endorse or promote products derived from
19 // this software without specific prior written permission.
20 //
21 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 //
33 // Authors: eduardo.ramos.testillano@gmail.com
34 //          cisco.tierra@gmail.com
35
36
37 #ifndef anna_timex_Meter_hpp
38 #define anna_timex_Meter_hpp
39
40 #include <anna/core/functions.hpp>
41
42 namespace anna {
43
44 namespace timex {
45
46 /**
47    Facilita la medicion de los tiempos empleados las distintas partes de nuestra aplicacion.
48
49    Permite calcular tiempos acumulados como tiempos individuales. Por ejemplo:
50
51    \code
52
53    #include <anna.timex.Meter.h>
54
55    void foo () {
56       timex::Meter meter;
57
58       goo ();
59       Millisecond gooTime = meter.getDelay ();
60
61       hoo ();
62       Millisecond goohooTime = meter.setControlPoint ();
63
64       joo ();
65       Millisecond jooTime = meter.getDelay ();
66    }
67    \endcode
68 */
69 class Meter {
70 public:
71   /**
72      Constructor
73      Inicializa la cuenta de temporizacion.
74   */
75   Meter() { a_timestamp = functions::millisecond(); a_topReference = 0; }
76
77   /**
78    * Constructor copia.
79    * Copia la cuenta de utilizacion de la instancia recibida como parametro.
80    * \param other Instancia de la copiar los parametros para calcular el tiempo transcurrido.
81    */
82   Meter(const Meter& other) : a_timestamp(other.a_timestamp) { a_topReference = 0; ;}
83
84   /**
85    * Inicializa la cuenta de temporizacion. Este metodo es invocado automaticamente desde el contructor la clase
86    * por lo que si vamos usar esta instancia para tomar un unica medida no es necesario invocarlo.
87    * \warning Elimina el punto de referencia temporal que puediera haberse establecido con #setTopReference.
88    * \return El número de milisegundos transcurridos desde la última vez que inicializamos la cuenta de temporizacion.
89    */
90   Millisecond setControlPoint() throw() {
91     Millisecond now = functions::millisecond();
92     Millisecond result = (now > a_timestamp) ? (now - a_timestamp) : (Millisecond)0;
93     a_timestamp = now;
94     clearTopReference();
95     return result;
96   }
97
98   /**
99    * Se da la posiblidad de establecer un punto de referencia temporal de forma
100    * que cuando se invoque a Meter::getDelay, el calculo de la diferencia de tiempo
101    * no se hará entre la marca de tiempo y el tiempo actual, sino la marca de
102    * tiempo y ésta marca de referencia.
103    *
104    * Esta funcionalidad ha sido requerida para medir el tiempo de ejecución "real"
105    * de tareas que se ejecutan dentro de un thread. Ya que puede pasar un tiempo
106    * indeterminado desde que se termina la tarea MT (momento en el que se establecerá
107    * la marca de tiempo) y el núcleo y demás partes pueden tener conocimiento de que
108    * esa tarea ha sido finalidad.
109    *
110    */
111   void setTopReference(const Millisecond & topReference) throw() { a_topReference = topReference; }
112
113   /**
114    * Elimina el punto de referencia temporal.
115    */
116   void clearTopReference() throw() { a_topReference = 0; }
117
118   /**
119    * Devuelve el número de milisegundos transcurridos desde la última vez que inicializamos la cuenta de temporización.
120    * Si se ha establecido un punto de referencia mediante #setTopReference, devolverá la diferencia entre el
121    * el punto de control y la referencia, en otro caso, devolverá la diferencia entre el punto de control y el
122    * momento actual.
123    * \return El número de milisegundos transcurridos desde la última vez que inicializamos la cuenta de temporizacion.
124    * \warning Si detecta algun fallo devolvera 0.
125    */
126   Millisecond getDelay() const throw() {
127     Millisecond now = (a_topReference == 0) ? functions::millisecond() : a_topReference;
128     return (now > a_timestamp) ? (now - a_timestamp) : (Millisecond)0;
129   }
130
131   /**
132    * Operador copia.
133    * \param timestamp Milisegundo en el que inicilizar la cuenta de esta instancia.
134    * \warning Elimina el punto de referencia temporal que puediera haberse establecido con #setTopReference.
135    * \see anna::functions::millisecond.
136    */
137   Meter& operator= (const Millisecond & timestamp) throw() { a_timestamp = timestamp; a_topReference = 0; return *this; }
138
139   /**
140    * Operador copia.
141    * \param other Instancia de la que copiar.
142    */
143   Meter& operator= (const Meter& other) throw() { a_timestamp = other.a_timestamp; a_topReference = other.a_topReference; return *this; }
144
145 private:
146   Millisecond a_topReference;
147   Millisecond a_timestamp;
148 };
149
150 }
151 }
152
153 #endif
154
155