To use gettimeofday you can do this:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
static float getTimeDiff(struct timeval *s, struct timeval *e);
void main()
{
struct timeval sTv, eTv;
gettimeofday(&sTv, NULL);
/* do work */
gettimeofday(&eTv, NULL);
printf("Time difference is %.2f seconds\n", getTimeDiff(&sTv, &eTv));
}
The getTimeDiff function works on the two timeval structures to compute the seconds elapsed. The source is simple, and as follows:
static float getTimeDiff(struct timeval *s, struct timeval *e)
{
struct timeval diff_tv;
diff_tv.tv_usec = e->tv_usec - s->tv_usec;
diff_tv.tv_sec = e->tv_sec - s->tv_sec;
if (s->tv_usec > e->tv_usec)
{
diff_tv.tv_usec += 1000000;
diff_tv.tv_sec--;
}
return (float) diff_tv.tv_sec + ((float) diff_tv.tv_usec / 1000000.0);
}
Furthermore, it should be noted that clock() does *NOT* return values based upon real time, rather it returns CPU time. If you want to know how much REAL TIME something takes then clock() is not the solution. For example:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void main()
{
int i, j, t;
clock_t clockSample[3];
clockSample[0] = clock();
sleep(2);
clockSample[1] = clock();
for (i = 0; i < 1024; i++)
for (j = 0; j < 1024; j++)
t = i * i + j;
clockSample[2] = clock();
for (i = 0; i < 3; i++)
{
printf("Clock sample %d is %lu\n", i, clockSample);
}
}
Upon running this code, you'll notice that the first two samples for clock are positioned squarely at 0. The sleep call, which will take around 2 seconds *real* time, has no effect on the second clock sample. Since sleep takes no CPU time, it is not calculated into the real time usage of the application by clock(). Similar behavior will be seen for other non-CPU (blocking) tasks the application incurs, such as waiting in a select call for socket I/O. The third clock sample, however, does incur CPU time as it is a CPU bound loop. Thus, the third sample will reflect the CPU time incurred by the loop. If, however, you had the crazy idea to insert (for example) a usleep in the loop, you would never calculate the additional real time incurred by the usleep.
So, beware that both methods, while equally useful, answer two different questions. clock() tells you CPU time used, the gettimeofday method tells you actual time elapsed.