switz
switz

Reputation: 25228

Get amount of time to run function in C

So this is pretty basic, but I don't really know C.

I want to find the number of milliseconds something takes to run, not clock (CPU) cycles.

I tried using

struct timeval start,end;
double dif;

gettimeofday(&start, 0);
//do stuff
gettimeofday(&end, 0);
dif = (end - start) / 1000.0;
printf("The time taken was %lf \n",dif);

I'm getting this error when I'm trying to compile:

bubble.c: In function ‘main’:
bubble.c:55: error: invalid operands to binary - (have ‘struct timeval’ and ‘struct timeval’)

Upvotes: 1

Views: 1073

Answers (5)

moshbear
moshbear

Reputation: 3322

Change

dif = (end - start) * 1000;

to

dif = (end.tv_sec - start.tv_sec) * 1000 
+ (end.tv_usec - start.tv_usec) / 1000;

In pseudocode:

Get the seconds part of the time delta
Multiply by 1000 to get milliseconds
Get the microseconds part of the time delta
Divide that part by 1000
Add that part to the milliseconds from seconds delta

Upvotes: 3

Ahmed Masud
Ahmed Masud

Reputation: 22412

On Linux the best way to achieve this is to use the times(2) interface rather than gettimeofday(2) have a read of the man page.

man 2 times.

It has exquisite fidelity.

Upvotes: 0

Keith
Keith

Reputation: 6834

You want:

dif = (end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) / 1000.0;

Note 1: You need the tv_sec to handle even a short duration crossing a second ticking over.

Note 2: Second term divides by a 1000.0 so as to use floating point rather than integer division.

Upvotes: 1

paulsm4
paulsm4

Reputation: 121881

  1. Make sure you're including the correct header ("#include ")

  2. Use "timersub()" to get the difference, instead of subtracting end-start:

http://linux.die.net/man/3/timeradd

'Hope that helps .. PSM

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 477640

For quick benchmark, I'd use clock() and CLOCKS_PER_SEC.

Here's some macro code I use:

#define CLOCK_TICK(acc, ctr)  ctr = std::clock()
#define CLOCK_TOCK(acc, ctr)  acc += (std::clock() - ctr)
#define CLOCK_RESET(acc) acc = 0
#define CLOCK_REPORT(acc) (1000. * double(acc) / double(CLOCKS_PER_SEC))

static clock_t t1a, t1c;


int main()
{
   while (true)
   {
     CLOCK_RESET(t1a);
     init_stuff();
     CLOCK_TICK(t1a, t1c);
     critical_function();
     CLOCK_TOCK(t1a, t1c);

     std::cout << "This round took " << CLOCK_REPORT(t1a) << "ms.\n";
   }
}

You can get a higher-resolution clock out of the new <chrono> header. The macros should be straight-forward to adapt.

Upvotes: 0

Related Questions