How to write a macro which gets runtime of a function?

386 views Asked by At

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.

1

There are 1 answers

4
ugoren On

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() );