First commit
[anna.git] / include / anna / timex / MicroMeter.hpp
1 // ANNA - Anna is Not 'N' 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_MicroMeter_hpp
38 #define anna_timex_MicroMeter_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.MicroMeter.h>
54
55    void foo () {
56       timex::MicroMeter meter;
57
58       goo ();
59       Microsecond gooTime = meter.getDelay ();
60
61       hoo ();
62       Microsecond goohooTime = meter.setControlPoint ();
63
64       joo ();
65       Microsecond jooTime = meter.getDelay ();
66    }
67    \endcode
68 */
69 class MicroMeter {
70 public:
71   /**
72      Constructor
73      Inicializa la cuenta de temporizacion.
74   */
75   MicroMeter() { a_timestamp = functions::microsecond(); a_topReference = (Microsecond)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   MicroMeter(const MicroMeter& other) : a_timestamp(other.a_timestamp) { a_topReference = (Microsecond)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   Microsecond setControlPoint() throw() {
91     Microsecond now = functions::microsecond();
92     Microsecond result = (now > a_timestamp) ? (now - a_timestamp) : (Microsecond)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 MicroMeter::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   void setTopReference(const Microsecond & topReference) throw() { a_topReference = topReference; }
111
112   /**
113    * Elimina el punto de referencia temporal.
114    */
115   void clearTopReference() throw() { a_topReference = (Microsecond)0; }
116
117   /**
118    * Devuelve el número de milisegundos transcurridos desde la última vez que inicializamos la cuenta de temporización.
119    * Si se ha establecido un punto de referencia mediante #setTopReference, devolverá la diferencia entre el
120    * el punto de control y la referencia, en otro caso, devolverá la diferencia entre el punto de control y el
121    * momento actual.
122    * \return El número de milisegundos transcurridos desde la última vez que inicializamos la cuenta de temporizacion.
123    * \warning Si detecta algun fallo devolvera 0.
124    */
125   Microsecond getDelay() const throw() {
126     Microsecond now = (a_topReference == 0) ? functions::microsecond() : a_topReference;
127     return (now > a_timestamp) ? (now - a_timestamp) : (Microsecond)0;
128   }
129
130   /**
131    * Operador copia.
132    * \param timestamp Milisegundo en el que inicilizar la cuenta de esta instancia.
133    * \warning Elimina el punto de referencia temporal que puediera haberse establecido con #setTopReference.
134    * \see anna::functions::microsecond.
135    */
136   MicroMeter& operator= (const Microsecond & timestamp) throw() { a_timestamp = timestamp; a_topReference = (Microsecond)0; return *this; }
137
138   /**
139    * Operador copia.
140    * \param other Instancia de la que copiar.
141    */
142   MicroMeter& operator= (const MicroMeter& other) throw() { a_timestamp = other.a_timestamp; a_topReference = other.a_topReference; return *this; }
143
144 private:
145   Microsecond a_topReference;
146   Microsecond a_timestamp;
147 };
148
149 }
150 }
151
152 #endif
153
154