0

Suppose we want to know how long function A runs, we can write code like this

    struct timeval tpstart,tpend;  
    gettimeofday(&tpstart,NULL); 
    A(); 
    gettimeofday(&tpend,NULL); 
    float timeuse= tpend.tv_sec-tpstart.tv_sec + (tpend.tv_usec-tpstart.tv_usec) / 1000000; 
    printf("Used Time:%f\n",timeuse); 

But how can I encapsulate it to a MACRO such Runtime(A), perhaps, Runtime(A, B, ...), sometime s several functions run together.

user3007735
  • 149
  • 1
  • 10
stonestrong
  • 337
  • 1
  • 5
  • 13

1 Answers1

1

If you don't care about the function's return value, life is easy:

#define Runtime(x)  do { \
    struct timeval tpstart,tpend;  \
    gettimeofday(&tpstart,NULL);   \
    x; \
    gettimeofday(&tpend,NULL); \
    float timeuse= tpend.tv_sec-tpstart.tv_sec + (float)(tpend.tv_usec-tpstart.tv_usec) / 1000000; \
    printf("Used Time:%f\n",timeuse); \
} while(0)

Runtime( A() );
Runtime( A() ; B() );
ugoren
  • 16,023
  • 3
  • 35
  • 65
  • You could even be more informative with `#x ": Used Time: %f"`. – Jens Gustedt Dec 11 '13 at 08:16
  • however when use Runtime(cudaKernel<<<1,1>>>()); it fails – stonestrong Dec 11 '13 at 08:45
  • @stonestrong, it looks that you are using CUDA? Be careful, other than you may think, CUDA is not C but C++. The preprocessor easily gets confused by C++ with differing syntax rules. Here in particular the comma in `1,1` is interpreted by the preprocessor as separation of macro arguments. To cope with that change the `#define` to `Runtime(...)`, three dots, and use `__VA_ARGS__`, two underscores infront and behind, in the place of `x`. – Jens Gustedt Dec 11 '13 at 09:14
  • @JensGustedt, an extra pair of parentheses can also help - `Runtime((cudaKernel<<<1,1>>>()));` - this way the macro knows it's only one parameter. But your variation of the macro is indeed more usable. – ugoren Dec 11 '13 at 15:37