Skip to content

Instantly share code, notes, and snippets.

@matthieuheitz
Last active February 5, 2016 17:32
Show Gist options
  • Save matthieuheitz/5d1321c6883f6ecdabfd to your computer and use it in GitHub Desktop.
Save matthieuheitz/5d1321c6883f6ecdabfd to your computer and use it in GitHub Desktop.
Timer functions to calculate execution time of a C/C++ program. Source: http://stackoverflow.com/questions/876901/calculating-execution-time-in-c
// 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
#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);
}

Run the time command on your program :

/usr/bin/time ./MyProgram
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment