Cómo usar clock() en C++


¿Cómo llamo a clock() en C++?

Por ejemplo, quiero probar cuánto tiempo tarda una búsqueda lineal en encontrar un elemento dado en un array.

Author: Borislav Kostov, 2010-07-10

6 answers

#include <iostream>
#include <cstdio>
#include <ctime>

int main() {
    std::clock_t start;
    double duration;

    start = std::clock();

    /* Your algorithm here */

    duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;

    std::cout<<"printf: "<< duration <<'\n';
}
 178
Author: Dolph,
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
2010-07-10 19:13:24

Una solución alternativa, que es portátil y con mayor precisión, disponible desde C++11, es usar std::chrono.

Aquí hay un ejemplo:

#include <iostream>
#include <chrono>
typedef std::chrono::high_resolution_clock Clock;

int main()
{
    auto t1 = Clock::now();
    auto t2 = Clock::now();
    std::cout << "Delta t2-t1: " 
              << std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1).count()
              << " nanoseconds" << std::endl;
}

Ejecutando esto ideone.com me dio:

Delta t2-t1: 282 nanoseconds
 53
Author: Martin G,
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
2015-12-02 05:46:17

clock() devuelve el número de marcas de reloj desde que se inició el programa. Hay una constante relacionada, CLOCKS_PER_SEC, que le dice cuántas marcas de reloj se producen en un segundo. Por lo tanto, puede probar cualquier operación como esta:

clock_t startTime = clock();
doSomeOperation();
clock_t endTime = clock();
clock_t clockTicksTaken = endTime - startTime;
double timeInSeconds = clockTicksTaken / (double) CLOCKS_PER_SEC;
 28
Author: Shirik,
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
2010-07-10 19:10:36

Al menos en Windows, el único mecanismo de medición prácticamente preciso es QueryPerformanceCounter (QPC). std:: chrono se implementa usándolo (desde VS2015, si lo usa), pero no es preciso en el mismo grado que usar QueryPerformanceCounter directamente. En particular, su afirmación de informar a 1 nanosegundo granularidad no es absolutamente correcta. Por lo tanto, si está midiendo algo que toma una cantidad muy corta de tiempo (y su caso podría ser tal caso), entonces debe usar QPC, o el equivalente para su sistema operativo. Me topé con esto al medir latencias de caché, y anoté algunas notas que podrían encontrar útiles, aquí; https://github.com/jarlostensen/notesandcomments/blob/master/stdchronovsqcp.md

 3
Author: SonarJetLens,
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
2018-02-25 18:12:53
#include <iostream>
#include <ctime>
#include <cstdlib> //_sleep()  --- just a function that waits a certain amount of milliseconds

using namespace std;

int main()
{

    clock_t cl;     //initializing a clock type

    cl = clock();   //starting time of clock

    _sleep(5167);   //insert code here

    cl = clock() - cl;  //end point of clock

    _sleep(1000);   //testing to see if it actually stops at the end point

    cout << cl/(double)CLOCKS_PER_SEC << endl;  //prints the determined ticks per second (seconds passed)


    return 0;
}

//outputs "5.17"
 0
Author: Garrett,
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
2015-08-27 04:36:40

Probablemente te podría interesar un temporizador como este : H: M :S. Msec.

El código en el sistema operativo Linux:

#include <iostream>
#include <unistd.h>

using namespace std;
void newline(); 

int main() {

int msec = 0;
int sec = 0;
int min = 0;
int hr = 0;


//cout << "Press any key to start:";
//char start = _gtech();

for (;;)
{
        newline();
                if(msec == 1000)
                {
                        ++sec;
                        msec = 0;
                }
                if(sec == 60)
                {
                        ++min;
                        sec = 0; 
                }
                if(min == 60)
                {
                        ++hr;
                        min = 0;
                }
        cout << hr << " : " << min << " : " << sec << " . " << msec << endl;
        ++msec;
        usleep(100000); 

}

    return 0;
}

void newline()
{
        cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
}
 0
Author: Färid Alijani,
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-12-29 16:06:32