matthieuheitz
2/5/2016 - 5:23 PM

Timer functions to calculate execution time of a C/C++ program. Source: http://stackoverflow.com/questions/876901/calculating-execution-time

Timer functions to calculate execution time of a C/C++ program. Source: http://stackoverflow.com/questions/876901/calculating-execution-time-in-c

Run the time command on your program :

/usr/bin/time ./MyProgram
#include <iostream>
#include <time.h>

void printTimeSince(clock_t tStart);

int main(void) {
    clock_t tStart = clock();
    /* Do your stuff here */
    printf("Time taken: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
    return 0;
}

void printTimeSince(clock_t tStart)
{
  printf("Time taken: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
}
// MACRO
#include <time.h>

#ifndef SYSOUT_F
#define SYSOUT_F(f, ...)      _RPT1( 0, f, __VA_ARGS__ ) // For Visual studio
#endif

#ifndef speedtest
#define speedtest(data)   for (long blockTime = NULL; (blockTime == NULL ? (blockTime = clock()) != NULL : false); SYSOUT_F(data "%.9fs", (double) (clock() - blockTime) / CLOCKS_PER_SEC))
#endif

// USAGE
speedtest("Block Speed: ")
{
    // The code goes here
}

// OUTPUT
// Block Speed: 0.127000000s