Skip to content

Instantly share code, notes, and snippets.

@natebenes
Created November 10, 2010 04:40
Show Gist options
  • Select an option

  • Save natebenes/670369 to your computer and use it in GitHub Desktop.

Select an option

Save natebenes/670369 to your computer and use it in GitHub Desktop.
A simple C function to time program execution down to the microsecond
// needed for timing
#include <stdio.h>
#include <sys/time.h>
// needed for wasting cpu time
#include <math.h>
long timeNow();
long timeNow(VOID)
{
// Special struct defined by sys/time.h
struct timeval tv;
// Long int to store the elapsed time
long fullTime;
// This only works under GNU C I think
gettimeofday(&tv, NULL);
// Do some math to convert struct -> long
fullTime = tv.tv_sec*1000000 + tv.tv_usec;
return fullTime;
}
int main(VOID)
{
long then, now, j;
int i;
// Initialize counter
then = timeNow();
j=0;
// BEGIN: wasting cpu time
for(i=1;i<1000000001;i++)
{
// calculate and sum a whole bunch of cube roots
j+=pow(i,1/3.0);
}
// So the compiler doesn't think the loop is trivial
j+=1;
// END: wasting cpu time
// grab time of completion
now = timeNow();
// display results :)
printf("elapsed: %d(us)\n",now-then);
// get more coffee
return 0;
}
cse misc/nbenes> a.out
elapsed: 2681671(us)
cse misc/nbenes>
#include <stdio.h>
#include <sys/time.h>
long timeNow(VOID)
{
// Special struct defined by sys/time.h
struct timeval tv;
// Long int to store the elapsed time
long fullTime;
// This only works under GNU C I think
gettimeofday(&tv, NULL);
// Do some math to convert struct -> long
fullTime = tv.tv_sec*1000000 + tv.tv_usec;
return fullTime;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment