Skip to content

Instantly share code, notes, and snippets.

@bricef
Created June 17, 2011 20:15
Show Gist options
  • Save bricef/1032215 to your computer and use it in GitHub Desktop.
Save bricef/1032215 to your computer and use it in GitHub Desktop.
Naive Timing of C Code.
#include <sys/time.h>
// ...
{
struct timeval t1, t2, diff;
double interval;
int i;
gettimeofday(t1, NULL);
for ( i = 0 ; i < 10000 ; i++ ){
my_time_critical_function();
}
gettimeofday(t2, NULL);
timersub(&t2, &t1, &diff);
interval = diff.tv_sec + (diff.tv_usec / 1000000.0 ) ;
printf("It took %f seconds\n", interval);
}
// ...
@oneamtu
Copy link

oneamtu commented Jun 17, 2011

If you're on linux you should look into using
clock_gettime(CLOCK_MONOTONIC, &tv);
it has a better resolution than gettimeofday!

@bricef
Copy link
Author

bricef commented Jun 17, 2011

@oneamtu: I'm writing a blogpost and embedding this. It's one step in the evolution of a timing solution, and in the end, I end up using Glib's Timers which are cross-platform and have the maximum accuracy on the platform (as I understand). I'll be mentioning clock_gettime() in the post though! Cheers for mentioning it!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment