2015-05-31 86 views
2

我需要隱藏指令才能以C語言獲取逝去的時間。例如,在下一個代碼中有幾條線指令來獲取函數foo的運行時間。隱藏C中的逝去時間

struct timeval start_keygen, end_keygen; 
long int diff_keygen_sec = 0; 
gettimeofday(&start_keygen, NULL); 
foo(r, w, h); 
gettimeofday(&end_keygen, NULL); 
timediff(start_keygen, end_keygen, &diff_keygen_sec); 

我的問題是如何來隱藏幾行於一體的功能,例如在 「的getTime」,即:

getTime(foo(r,w,h)) 
+1

雖然難看,怎麼關於宏? –

+0

@ m.s。這不是醜陋的! –

回答

5

你可以使用宏:

#define TIME(e, res) do{struct timeval start_keygen, end_keygen; \ 
      res = 0; \ 
      gettimeofday(&start_keygen, NULL); \ 
      e; \ 
      gettimeofday(&end_keygen, NULL); \ 
      timediff(start_keygen, end_keygen, &res)} while(0) \ 

然後你可以這樣做:

long int myRes; 
TIME(foo(r,w,h), myRes); 

這將擴展到您擁有的代碼,每次在編譯時使用它,並將結果綁定到myRes

+0

@iharob,謝謝,編輯。 – Matt

2

宏真的是你想要的,但不是通過函數調用,你可以把它一點點不同,它的語法類似的功能,這是不太難看

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 

#include <sys/time.h> 
#include <unistd.h> 

#define TimedExecution(elapsed, function, ...)    \ 
    do {              \ 
     struct timeval start;        \ 
     struct timeval end;         \ 
     gettimeofday(&start, NULL);       \ 
     function(__VA_ARGS__);        \ 
     gettimeofday(&end, NULL);       \ 
     *((long int *) elapsed) = timevaldiff(&start, &end); \ 
    } while (0) 

long int 
timevaldiff(struct timeval *starttime, struct timeval *finishtime) 
{ 
    long int msec; 

    msec = (finishtime->tv_sec - starttime->tv_sec) * 1000; 
    msec += (finishtime->tv_usec - starttime->tv_usec)/1000; 

    return msec; 
} 

void 
execute(const char *message) 
{ 
    for (int i = 0 ; i < 3 ; ++i) 
    { 
     fprintf(stdout, "%s\n", message); 
     sleep(1); 
    } 
} 

int 
main(void) 
{ 
    long int elapsed; 
    TimedExecution(&elapsed, execute, "Hello World!"); 
    fprintf(stdout, "Executed in: %ld msec\n", elapsed); 
    return 0; 
}