Updated license
[anna.git] / include / anna / core / util / DelayMeter.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_core_util_DelayMeter_hpp
38 #define anna_core_util_DelayMeter_hpp
39
40 #include <string>
41
42 namespace anna {
43
44 /**
45    Facilita la medicion de los tiempos empleados las distintas partes de nuestra aplicacion.
46
47    Permite calcular tiempos acumulados como tiempos individuales. Por ejemplo:
48
49    \code
50
51    #include <anna/core/DelayMeter.hpp>
52
53    void foo () {
54       DelayMeter <_TimeUnit> meter;
55
56       goo ();
57       _TimeUnit gooTime = meter.getValue ();
58
59       hoo ();
60       _TimeUnit goohooTime = meter.setControlPoint ();
61
62       joo ();
63       _TimeUnit jooTime = meter.getValue ();
64    }
65    \endcode
66
67    Dónde _TimeUnit podria ser anna::Second, anna::Millisecond, anna::Microsecond
68 */
69 template <class _TimeUnit> class DelayMeter {
70 public:
71   /**
72      Constructor
73      Inicializa la cuenta de temporizacion.
74   */
75   DelayMeter() { a_timestamp = _TimeUnit::getTime(); }
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   DelayMeter(const DelayMeter& other) : a_timestamp(other.a_timestamp), a_topReference(other.a_topReference) { ;}
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   void setControlPoint() throw() {
91     a_timestamp = _TimeUnit::getTime();
92     clearTopReference();
93   }
94
95   /**
96    * Inicializa la cuenta de temporizacion. Este metodo es invocado automaticamente desde el contructor la clase
97    * por lo que si vamos usar esta instancia para tomar un unica medida no es necesario invocarlo.
98    * \warning Elimina el punto de referencia temporal que puediera haberse establecido con #setTopReference.
99    * \return El número de milisegundos transcurridos desde la última vez que inicializamos la cuenta de temporizacion.
100    *
101    * \param timestamp Valor de referencia a establecer.
102    */
103   void setControlPoint(const _TimeUnit& timestamp) throw() {
104     a_timestamp = timestamp;
105     clearTopReference();
106   }
107
108   /**
109    * Se da la posiblidad de establecer un punto de referencia temporal de forma
110    * que cuando se invoque a DelayMeter::getValue, el calculo de la diferencia de tiempo
111    * no se hará entre la marca de tiempo y el tiempo actual, sino la marca de
112    * tiempo y ésta marca de referencia.
113    *
114    * Esta funcionalidad ha sido requerida para medir el tiempo de ejecución "real"
115    * de tareas que se ejecutan dentro de un thread. Ya que puede pasar un tiempo
116    * indeterminado desde que se termina la tarea MT (momento en el que se establecerá
117    * la marca de tiempo) y el núcleo y demás partes pueden tener conocimiento de que
118    * esa tarea ha sido finalidad.
119    */
120   void setTopReference(const _TimeUnit& topReference) throw() { a_topReference = topReference; }
121
122   /**
123    * Elimina el punto de referencia temporal.
124    */
125   void clearTopReference() throw() { a_topReference = _TimeUnit(0); }
126
127   /**
128    * Inicializa el valor del punto de referencia.
129    */
130   void clear() throw() { a_timestamp = 0; }
131
132   /**
133    * Devuelve el número de milisegundos transcurridos desde la última vez que inicializamos la cuenta de temporización.
134    * Si se ha establecido un punto de referencia mediante #setTopReference, devolverá la diferencia entre el
135    * el punto de control y la referencia, en otro caso, devolverá la diferencia entre el punto de control y el
136    * momento actual.
137    * \return El número de milisegundos transcurridos desde la última vez que inicializamos la cuenta de temporizacion.
138    * \warning Si detecta algun fallo devolvera 0.
139    */
140   _TimeUnit getValue() const throw() {
141     a_now = (a_topReference == _TimeUnit(0)) ? _TimeUnit::getTime() : a_topReference;
142     return (a_now > a_timestamp) ? (a_now - a_timestamp) : _TimeUnit(0);
143   }
144
145   /**
146    * Devuelve el número de milisegundos transcurridos desde la última vez que inicializamos la cuenta de temporización.
147    * Si se ha establecido un punto de referencia mediante #setTopReference, devolverá la diferencia entre el
148    * el punto de control y la referencia, en otro caso, devolverá la diferencia entre el punto de control y el
149    * momento actual.
150    * \param now Valor temporal tomado como referencia.
151    * \return El número de milisegundos transcurridos desde la última vez que inicializamos la cuenta de temporizacion.
152    * \warning Si detecta algun fallo devolvera 0.
153    */
154   _TimeUnit getValue(const _TimeUnit& now) const throw() {
155     return ((a_now = now) > a_timestamp) ? (a_now - a_timestamp) : _TimeUnit(0);
156   }
157
158   /**
159    * Devuelve el tiempo que se usó como referencia al calcular el retardo en #getValue
160    * \return El tiempo que se usó como referencia al calcular el retardo en #getValue
161    */
162   const _TimeUnit& getNow() const throw() { return a_now; }
163
164   /**
165    * Operador copia.
166    * \param other Instancia de la que copiar.
167    */
168   DelayMeter& operator= (const DelayMeter& other) throw() { a_timestamp = other.a_timestamp; a_topReference = other.a_topReference; return *this; }
169
170   /**
171    * Compara el retardo acumulado por esta instancia con el valor recibido.
172    * \param left Valor numérico con el comparar.
173    * \return \em true si el retardo acumulado es mayor que el parámetro recibido o \em false en otro caso.
174    */
175   bool operator> (const _TimeUnit& left) const throw() { return getValue() > left; }
176
177   /**
178    * Compara el retardo acumulado por esta instancia con el valor recibido.
179    * \param left Valor numérico con el comparar.
180    * \return \em true si el retardo acumulado es mayor que el parámetro recibido o \em false en otro caso.
181    */
182   bool operator< (const _TimeUnit& left) const throw() { return getValue() < left; }
183
184   /**
185    * Devuelve la cadena que muestra el tiempo medido por esta instancia.
186    * \return la cadena que muestra el tiempo medido por esta instancia.
187    */
188   std::string asString() const throw() { return getValue().asString(); }
189
190   /**
191    * Devuelve la cadena de depuración de esta instancia.
192    * \param whatis Texto con el nombre lógico de esta instancia.
193    * \return la cadena de depuración de esta instancia.
194    */
195   std::string asDebugString(const char* whatis) const throw() {
196     std::string result(whatis);
197     result += " { TopReference: ";
198     result += a_topReference.asString();
199     result += " | TimeStamp: ";
200     result += a_timestamp.asString();
201     result += " | Now: ";
202     result += a_now.asString();
203     return result += " }";
204   }
205
206 private:
207   _TimeUnit a_topReference;
208   _TimeUnit a_timestamp;
209   mutable _TimeUnit a_now;
210 };
211
212 }
213
214 #endif
215
216