Balerion_the_black
Balerion_the_black

Reputation: 121

How to measure computing time

In my homework assignment I am supposed to measure computation time for different algorithms. I am given the following functions "beginTime" and "endTime" to do it. However, when I compile them, together with my algorithm, the compiler shows that "start" and "stop" are undefined. But I don't know how to define them (what type they should be), and how to make the "start" in "endTime" refer to the "start" in "beginTime". How can I fix it? Also, how can I print the returned value?

 void
beginTime ()
{
gettimeofday (&start, 0);
}

float
endTime ()
{
gettimeofday (&stop, 0);

double begin = (double) start.tv_sec + (double) (start.tv_usec / 1.E6);

double end = (double) stop.tv_sec + (double) (stop.tv_usec / 1.E6);

return end - begin;
}

Upvotes: 1

Views: 389

Answers (2)

chrisaycock
chrisaycock

Reputation: 37930

The man page for gettimeofday() lists the relevant type:

struct timeval {
    time_t      tv_sec;     /* seconds */
    suseconds_t tv_usec;    /* microseconds */
};

You'll have to save start somewhere. The worst-case scenario (since this is a homework assignment) might be to just make it a global variable. In a production environment, your beginTime() function would actually return a double for the starting time, which you would simply record before running the algorithm you are trying to time.

Upvotes: 1

paddy
paddy

Reputation: 63471

If you look up the function gettimeofday, you'll see it takes struct timeval. Your code should look like this:

#include <sys/time.h>

static struct timeval start, stop;

void beginTime()
{
    gettimeofday (&start, 0);
}

float endTime()
{
    gettimeofday (&stop, 0);
    double begin = (double) start.tv_sec + (double) (start.tv_usec / 1.E6);
    double end = (double) stop.tv_sec + (double) (stop.tv_usec / 1.E6);
    return end - begin;
}

Upvotes: 3

Related Questions