Tip C++: Medir tiempo de ejecución
Última actualización: 13/03/2010
Últimamente me preocupo bastante con el tema de la optimización del código y es sorprenderte ver como en ocasiones unas simples modificaciones hacen que tus librerías o programas se ejecuten varias veces más rápido. Para medir el tiempo de ejecución de un determinado bloque de código tenemos varias opciones. En esta entrada os dejo tres formas para calcular el tiempo en vuestros programas.
Las alternativas utilizadas son:
- Usar la función clock() junto a la constante CLOCKS_PER_SEC. El inconveniente de este método es que tiene una precisión de segundos.
- Usar la función clock() junto a la función difftime().
- Usar la función ftime().
Sin darle más vueltas al asunto os dejo un ejemplo.
// ======================================================================
//
// Filename: times.cpp
//
// Description:
//
// Version: 1.0
// Created: 13/03/10 13:43:00
// Revision: none
// Compiler: g++
//
// Author: piponazo, piponazo@plagatux.es
// Company: http://plagatux.es
//
// ======================================================================
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <sys/timeb.h>
using namespace std;
int main()
{
clock_t startC, finishC;
struct timeb startT, finishT;
unsigned int elements=100000;
unsigned int operations=10000;
unsigned int seconds, milliseconds;
startC = clock();
ftime(&startT);
//----------------------------------------------------------------------
// Processes
//----------------------------------------------------------------------
int *a = new int[elements];
int *b = new int[elements];
for (unsigned int i=0; i<elements; i++)
{
a[i] = rand();
b[i] = rand();
}
for (unsigned int j=0; j<operations; j++)
for (unsigned int i=0; i<elements; i++)
a[i] += b[i];
delete [] a;
delete [] b;
finishC = clock();
ftime(&finishT);
seconds = finishT.time - startT.time - 1;
milliseconds = (1000 - startT.millitm) + finishT.millitm;
cout << "Time (clock): " << (finishC - startC)/CLOCKS_PER_SEC << endl;
cout << "Time (difftime): " << difftime(finishC, startC) << endl;
cout << "Time (ftime): " << (milliseconds + seconds * 1000) << endl;
}
Last update: 13/03/2010
Lately I’m very concerned with optimizing of code. It’s surprising to see how sometimes a few simple modifications make your libraries or programs run several times faster. To measure the time of execution of a specific block of code we have several options. In this post I show you three ways for measuring the execution time of your programs.
The three approaches are:
- Use the clock() function in conjunction with the constant CLOCKS_PER_SEC. The drawback of this approach is that the time is given in seconds and not with milli-seconds.
- Use the clock() function in conjunction with the difftime() one.
- Use the ftime() function.
Without beating more around the bush I show you an example. (See in the spanish section)
loading...




loading...
si deseas mas precision, en cetesimas de segundo puedes utilizar la libreris sys/time.h
#include
int main(int argc, char **argv)
{
clock_t t1,t2;
t1=times(NULL);
….
t2=times(NULL);
printf (“%ld\n”,(long)(t2-t1));
return 0;
}
loading...
Hola yoni de la forma que he indicado también se consigue precisión en centésimas de segundo. Sin embargo he intentado probar la forma que has indicado y:
1º La función times() no existe, así que he probado con time().
2º Me da el número de segundos pero como un número entero.