C++: Medición de tiempo con 'chrono'

1 comment
¿Necesitas medir tiempos de ejecución y no sabes cómo? 
Has dado con el blog adecuado ;)

Si no tienes mucho tiempo puedes copiar directamente el código que está al final para salir del paso pero, eh, no te acostumbres a copiar y pegar. Es bueno ver qué y cómo programan los demás pero tienes que intentar entenderlo.

En primer lugar aclarar que utilizo la biblioteca chrono incluida en el estándar C++11. Para poder usarla tienes que hacer dos cosas:
  1. Añadir ' #import <chrono> ' al inicio de tu código.
  2. Añadir el flag ' -std=c++0x ' a la hora de compilar.
Ya sabes cómo añadirla, así que vamos al lío.

Tienes toda la documentación aquí (enlace) por si quieres consultar otras funciones. Yo me voy a centrar en 'high_definition_clock'.

En primer lugar tienes que añadir estas dos líneas de código que te permitirán ahorrarte escribir 'std::chrono::' antes de llamar a métodos u objetos dentro del ámbito de la biblioteca chrono.
using namespace std;
using namespace std::chrono;
A continuación crea dos variables que contendrán el tiempo antes y después de la ejecución:
double time;
duration<double> interval;
high_resolution_clock::time_point start, end;

start = high_resolution_clock::now();
// Función que quieras medir.
end = high_resolution_clock::now();
Posteriormente se calcula el intervalo de tiempo y se almacena en una variable de tipo double:
interval = duration_cast>(end - start);
  
time = interval.count();
Para ahorrarte tiempo puedes usar el objeto Clock que he implementado y que es de código libre (está en GitHub y lo muestro a continuación). Para usarlo tienes, de nuevo qué pesado, dos opciones:

  1. Copias el código dentro de tu programa. (Que no se te olvide incluir la bilbioteca chrono)
  2. Descargarte el archivo e incluirlo con '#include "clock.hpp"'. 

 En ambos casos tendrás que añadir el flag que mencioné al principio cuando compiles, '-std=c++0x'. Un simple ejemplo de uso:
Clock my_clock;
double time;

my_clock.start();
// Lo que quieras medir.
time = my_clock.now();
Fácil, ¿Verdad?

Aquí puedes ver/descargar el código al completo:
/*
MIT License
Copyright (c) 2016 Alberto Sola Comino
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/*
Clock ( Time Measurement )
==========================
Simple ADT for time measurement using 'chrono' library and 'high_definition_clock'.
When you create a 'Clock' object it sets automatically the start time.
It provides you two methods:
- start() : It sets the start time to the current time.
- now() : It returns a double with the time between start
and the moment when you call it.
Easy, right? You only need to add ' #include "clock.hpp" ' to your code
(or nothing if you copy it), and the C++11 flag, ' -std=c++0x ' when compiling.
Alberto Sola Comino - 2016
*/
#include <chrono>
using namespace std;
using namespace std::chrono;
class Clock{
private:
// Holds the start time
high_resolution_clock::time_point start_time;
public:
Clock(){
start();
}
void start(){
/*
Set the 'start' time to the current time.
*/
start_time = high_resolution_clock::now();
}
double now(){
/*
It returns a double with the time between start and the moment when you call it.
*/
high_resolution_clock::time_point end = high_resolution_clock::now();
duration<double> time = duration_cast<duration<double>>(end - start_time);
return time.count();
}
};
view raw clock.hpp hosted with ❤ by GitHub
¡Saludos!

1 comentario: