Skip to content

Instantly share code, notes, and snippets.

@error454
Created December 8, 2011 20:01
Show Gist options
  • Save error454/1448313 to your computer and use it in GitHub Desktop.
Save error454/1448313 to your computer and use it in GitHub Desktop.
Simple Function Timing for C/C++
//The includes required
#include "time.h"
#include "stdio.h"
FILE *logfile;
/*
* Compares two time intervals and returns the time
* difference in milliseconds.
*/
int getTimeDiff(timeval t1, timeval t2) {
long elapsed_seconds = t2.tv_sec - t1.tv_sec;
long elapsed_useconds = t2.tv_usec - t1.tv_usec;
//Return time difference in milliseconds
return ((elapsed_seconds) * 1000 + elapsed_useconds / 1000.0) + 0.5;
}
/*
* Returns the current time in a timeval struct
*/
timeval getTime(void) {
timeval currentTime;
gettimeofday (&currentTime, NULL);
return currentTime;
}
//...
//Initialization, most likely called in constructor or via onCreate
//we append to the log file, so be sure to delete it between runs
logfile = fopen("/sdcard/yourlog.log", "a");
//...
//...
//Cleanup, most likely in your destructor or via onPause.
//Don't forget to call this, if you do your log file won't
//be written.
fclose(logfile);
//...
void aFunctionToTime(){
//The variables to store time and intervals
timeval t1, t2, t3, t4, t5;
int i1, i2, i3, i4;
//Now spread your time variables like seeds in the wind...
t1 = getTime();
someLongRunningFunction();
t2 = getTime();
//... More stuff to time
t3 = getTime(); //etc...
//All done, time to calculate intervals and scribble to the log
i1 = getTimeDiff(t1, t2);
i2 = getTimeDiff(t2, t3);
i3 = getTimeDiff(t3, t4);
i4 = getTimeDiff(t4, t5);
fprintf(logfile, "%d %d %d %d\n", i1, i2, i3, i4);
//Import to excel as space delimited
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment