Cómo cronometrar una función en milisegundos sin boost:: timer


Estoy usando boost 1.46 que no incluye boost::timer, ¿De qué otra manera puedo cronometrar mis funciones?

Actualmente estoy haciendo esto:

time_t now = time(0);
<some stuff>
time_t after = time(0);

cout << after - now << endl; 

Pero solo da la respuesta en segundos, por lo que si la función toma

Gracias

Author: Lightness Races in Orbit, 2013-02-26

5 answers

En linux o Windows:

#include <ctime>
#include <iostream>

int
main(int, const char**)
{
     std::clock_t    start;

     start = std::clock();
     // your test
     std::cout << "Time: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms" << std::endl;
     return 0;
}

Buena suerte;)

 26
Author: Quentin Perez,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-20 20:13:55

Usando std::chrono:

#include <chrono>
#include <thread>
#include <iostream>

// There are other clocks, but this is usually the one you want.
// It corresponds to CLOCK_MONOTONIC at the syscall level.
using Clock = std::chrono::steady_clock;
using std::chrono::time_point;
using std::chrono::duration_cast;
using std::chrono::milliseconds;
using namespace std::literals::chrono_literals;
using std::this_thread::sleep_for;

int main()
{
    time_point<Clock> start = Clock::now();
    sleep_for(500ms);
    time_point<Clock> end = Clock::now();
    milliseconds diff = duration_cast<milliseconds>(end - start);
    std::cout << diff.count() << "ms" << std::endl;
}

std::chrono es C++11, std::literals es C++14 (de lo contrario necesita milliseconds(500)).

 17
Author: o11c,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-07 17:50:50

Resulta que hay una versión de time en boost 1.46 (solo en una ubicación diferente). Gracias a @jogojapan por señalarlo.

Se puede hacer así:

#include <boost/timer.hpp>

timer t;
<some stuff>
std::cout << t.elapsed() << std::endl;

O alternativamente usando libs de std como @Quentin Pérez ha señalado (y aceptaré como es lo que se preguntó originalmente)

 9
Author: Aly,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-26 15:25:19

Basándose en la solución de Quentin Perez, puede pasar una función arbitraria a time usando std::function y una lambda.

#include <ctime>
#include <iostream>
#include <functional>

void timeit(std::function<void()> func) {
    std::clock_t start = std::clock();

    func();

    int ms = (std::clock() - start) / (double) (CLOCKS_PER_SEC / 1000);

    std::cout << "Finished in " << ms << "ms" << std::endl;
}

int main() {
    timeit([] {
        for (int i = 0; i < 10; ++i) {
            std::cout << "i = " << i << std::endl;
        } 
    });

    return 0;
}
 3
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-05 23:19:37

Puede usar un largo para mantener el valor de tiempo actual como un valor inicial, y luego convertir la hora actual en un doble. aquí hay algunos fragmentos de código para usar como ejemplo.

#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <sys/types.h>
#include <sys/timeb.h>
int main()
{

struct      _timeb tStruct;
double      thisTime;
bool        done = false;
long        startTime;

 struct _timeb
 {
 int   dstflag;   // holds a non-zero value if daylight saving time is in effect
 long  millitm;   // time in milliseconds since the last one-second hack
 long  time;      // time in seconds since 00:00:00 1/1/1970
 long  timezone;  // difference in minutes moving west from UTC

 };

  _ftime(&tStruct); // Get start time

thisTime = tStruct.time + (((double)(tStruct.millitm)) / 1000.0); // Convert to double
startTime = thisTime;                                             // Set the starting time (when the function begins)


while(!done)     // Start an eternal loop
    {
    system("cls");  // Clear the screen
    _ftime(&tStruct);    // Get the current time
    thisTime = tStruct.time + (((double)(tStruct.millitm)) / 1000.0); // Convert to double
    // Check for 5 second interval to print status to screen
    cout << thisTime-startTime; // Print it. 

    }
}
 2
Author: valkn0t,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-26 15:26:52