3

I'm trying to pass pointers to two struct timevals to a function that would output the elapsed time between the two in a C program. However, even if I dereference these pointers, nvcc throws the error "expression must have class type" (this is a CUDA program). Here is the relevant code from main():

struct timeval begin, end;
if (tflag) { HostStartTimer(&begin) };
// CUDA Kernel execution
if (tflag) { HostStopTimer(&begin, &end); }

And the function definition for HostStopTimer():

void HostStopTimer(struct timeval *begin, stuct timeval *end) {
    long elapsed;
    gettimeofday(end, NULL);
    elapsed = ((*end.tv_sec - *begin.tv_sec)*1000000 + *end.tv_usec - *begin.tv_usec);
    printf("Host elapsed time: %ldus\n", elapsed);
 }

The line causing the error is the assignment to elapsed. I don't have much experience using structs in C, much less passing pointers to structs to functions, so I'm not sure what is causing the error.

Andrew
  • 1,081
  • 1
  • 8
  • 19
  • try: elapsed = ((end->tv_sec - begin->tv_sec)*1000000 + end->tv_usec - begin->tv_usec); – fazo Apr 14 '11 at 22:29

2 Answers2

7

The . operator has higher precedence than the * operator, so expressions like *end.tv_sec attempt to first evaluate end.tv_sec (which isn't possible since end is a pointer) and then dereference the result.

You should use (*end).tv_sec or end->tv_sec instead.

David Brown
  • 13,336
  • 4
  • 38
  • 55
2

You should write elapsed = (((*end).tv_sec - (*begin).tv_sec)*1000000 + (*end).tv_usec - (*begin).tv_usec); or use the -> operator.

the . operator can be used only on structs, not on pointers to structs, for example: (*begin).tv_sec and not begin.tv_sec because begin is a pointer to struct. the operator -> is just a "shortcut" for the above, for example (*begin).tv_sec is the same as begin->tv_sec

MByD
  • 135,866
  • 28
  • 264
  • 277