Created
June 17, 2011 20:15
-
-
Save bricef/1032215 to your computer and use it in GitHub Desktop.
Naive Timing of C Code.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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: 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
If you're on linux you should look into using
clock_gettime(CLOCK_MONOTONIC, &tv);
it has a better resolution than gettimeofday!